Utilizing JavaScript to implement a single method across multiple objects

Recently, I encountered a problem while trying to use the prototype method to apply the same function or variable to multiple objects. Despite creating numerous objects in the following manner:

var item = {
  a: {
    aa: "lalala",
    ab: 1,
    something: 3
  },
  b: {
    ba: "jfjb",
    bb: 2,
    something: 4
  }
}

When attempting to implement the prototype method like so:

item.prototype.bob = 2;

An error message stating

"Cannot set property 'bob' of undefined"

was displayed. The same issue arose when trying to create a method:

item.prototype.bob = function() {
   100 - this.something;
   this.something++;
}

I am at a loss as to what I might be doing incorrectly. Is there an alternative method that can achieve the desired outcome across multiple objects?

Answer №1

You may be caught up in the confusion of classes and object instances. What you actually have is an anonymous object, not a class instance. Remember, item represents the instance whereas the class itself is denoted by Item.

In the code snippet below, notice the declaration of a class (Item with a capital 'I'), creation of an instance (item), and modification of the prototype belonging to the class. This demonstrates how setting a property on the prototype allows you to access it through the instance.

var Item = function() {
  a = {
    aa: "lalala",
    ab: 1,
    something: 3
  };
  b = {
    ba: "jfjb",
    bb: 2,
    something: 4
  };
}

var item = new Item();

Item.prototype.bob = 'x';

alert(item.bob);

Answer №2

The traditional approach is:

function Individual(first, last) {
    this.first = first;
    this.last = last;
}

Individual.prototype.sayHello = function() {
    console.log(this.first + " greets you");
}

var john = new Individual("John", "Doe");

john.sayHello();

It is important to note that the prototype property belongs to the constructor (the function object we use with new to create the instance), not the individual instance itself.

In ECMAScript 6, you can express this more concisely as:

class Person {
    constructor(first, last) {
        this.first = first;
        this.last = last;
    }

    sayHello() {
        console.log(this.first + " greets you");
    }
}

new Person("John", "Doe").sayHello();

Answer №4

Your item is considered an independent object without a constructor, which means you are unable to define or set it on the prototype. As a result, your code will throw an error.

To resolve this issue, you can restructure your code as shown below:

function item(x, y){
   this.x = x;
   this.y = y;
}
function example(aa, bb, something){
   this.aa = aa;
   this.bb = bb;
   this.something = something
}
item.prototype.value = 2;
item.prototype.method2 = function() {
   100 - this.something;
   this.something++;
}

I hope this explanation clarifies the situation for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to update my profile picture without having to constantly refresh the page after uploading it?

Here is the code for my profile page. I am considering using a callback along with another useEffect function, but I'm unsure. Please help me in finding a solution. For now, let's ignore all the code related to deleting, saving, and handling ingr ...

Ways to implement a parallax effect by changing images within a specific div on scrolling with the mouse

First and foremost, thank you for taking the time to review my question. I am currently developing a website and I need to implement a vertical image transition effect within a selected division, similar to a parallax effect. Within this div, there are 3 ...

Struggling with implementing Mobile Navigation menu

I'm struggling to implement a mobile menu for my website. After adding the necessary code, when I view the page in a mobile viewport, all I see are two sets of periods ("..."). However, unlike in the code snippet provided, the list does appear on the ...

What is the best way to make a container 100% tall and display a navigation bar?

Struggling to properly render my React page This is what I have: ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router /> </Provider> </React.StrictMode>, document.getEl ...

The parameter 'string | JwtPayload' cannot be assigned to the parameter 'string'

Utilizing Typescript alongside Express and JWT for Bearer Authorization presents a specific challenge. In this situation, I am developing the authorize middleware with JWT as specified and attempting to extricate the current user from the JWT token. Sampl ...

Automatically bundle and release an NPM package using the libnpm library

My goal is to automate publishing to NPM within my CI/build system. I came across libnpmpublish, which appears to be the right tool for the job. However, it clearly states that it does not package code into a tarball, even though the publish API requires a ...

Set a variable in Node.js to capture the return value of res.json

Embarking on the creation of a social network using Node.js, I must admit that I am quite new to this field. This marks my inaugural post on the subject and I sincerely hope for your understanding. Within my social network project, I aim to implement an a ...

The cookies() function in NextJS triggers a page refresh, while trpc consistently fetches the entire route

Is it expected for a cookies().set() function call to trigger a full page refresh in the new Next 14 version? I have a chart component that fetches new data at every interval change, which was working fine when fetching the data server-side. However, since ...

challenges surrounding the use of getElementByTagName

Within my webpage, I have implemented two select elements, both containing multiple options. However, I am facing an issue where I can only access the options from the first select box using getElementByTagName("options"), and unable to retrieve the option ...

Nesting Multiple Click Directives in AngularJS

I am facing a situation where I have two directives in play – one is enclosed within a specific view, while the other is applied to the container of that view. <div id="content" data-panel='{{ pNav }}' close-content> <div class="i ...

$injector.modulerr problem

After spending a considerable amount of time analyzing every line of code, I can't seem to pinpoint any errors. Here is what I have: HTML: <body ng-app='myApp'> <div class="wrapper"> <nav> <ul ng-controller="pat ...

preserve functionality when switching between pages

I have created two simple functions that can change the background color of the body. <script type="text/javascript"> function switchBackground(color){ document.body.bgColor=color; } </script> I am using links with onclick to execute thes ...

I experienced an issue with Firestore where updating just one data field in a document caused all the other data to be wiped out and replaced with empty Strings

When updating data in my Firestore document, I find myself inputting each individual piece of data. If I try to edit the tag number, it ends up overwriting the contract number with an empty string, and vice versa. This issue seems to stem from the way th ...

"Implementing Nested Actions in Vuex: A Guide on Calling Actions within Actions

I am currently working on a small Vue App with a Rails API where I am using Vue, Vue-Resource, and Vuex. I have successfully fetched all users from the database and now I am trying to update one of them. The patch operation for updating the user is working ...

"Apply a class to a span element using the onClick event handler in JavaScript

After tirelessly searching for a solution, I came across some answers that didn't quite fit my needs. I have multiple <span id="same-id-for-all-spans"></span> elements, each containing an <img> element. Now, I want to create a print ...

Creating dynamic and fluid motion with Bezier curves on canvas

I am currently working on creating a line that spans across the canvas from left to right. In these early stages of development, I am using a step-by-step animation approach with the following function: timer = window.setInterval(draw_line, 30); Here is ...

Scrolling back to the top of the page using Jquery instead of a specific div

Check out the code for my project here. The isotope feature is functioning correctly, however, when clicking on the image, instead of scrolling to the navigation under the red box as intended, the page scrolls all the way to the top. If I modify the follo ...

Problem with selecting odd and even div elements

I have a div populated with a list of rows, and I want to alternate the row colors. To achieve this, I am using the following code: $('#PlatformErrorsTableData').html(table1Html); $('#PlatformErrorsTableData div:nth-child(even)').css(" ...

Refreshing a div using ajax technology

I am attempting to use Ajax to update an h3 element with the id data. The Ajax call is making a get request to fetch data from an API, but for some reason, the HTML content is not getting updated. This is how the JSON data looks: {ticker: "TEST", Price: 7 ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...