Reputation: 95
I have heard about the prototype method to apply one function or variable to several objects. But it does not work for me somehow. I created many objects kind of like this:
var item = {
a: {
aa: "lalala",
ab: 1,
something: 3
},
b: {
ba: "jfjb",
bb: 2,
something: 4
}
}
But when I know use the prototype method
item.prototype.bob = 2;
it does not work and shows me the error
Cannot set property 'bob' of undefined"
Same for a method
item.prototype.bob = function() {
100 - this.something;
this.something++;
}
Do you know what I do wrong or is there a different method to apply the same variable or function to many objects?
Upvotes: 0
Views: 107
Reputation: 70574
The classic way is
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.greet = function() {
console.log(this.firstName + " says hello");
}
var pete = new Person("Peter", "Pan");
pete.greet();
Note that the prototype attribute is on the constructor (the function object we invoke with new
to construct the object), not the constructed object itself.
In ECMAScript 6, you'll be able to write this in a more compact way:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
greet() {
console.log(this.firstName + " says hello");
}
}
new Person("Peter", "Pan").greet();
Upvotes: 1
Reputation: 116140
You confuse classes with object instances. You just have an anonymous object. item
is the instance, not the class.
In the snippet below, a class is declared (Item
, with capital i), an instance is created (item
), and the prototype of the class is modified. You will see then that you can set a property on the prototype and read it though the instance, if you like.
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);
Upvotes: 1
Reputation: 7496
Here your item is an object by itself,it does not has any constructor, so you cannot define or set on prototype.Your code throws error
To fix this, it has to be something like the below
function item(a,b){
this.a=a;
this.b=b;
}
function a(aa,ab,something){
this.aa=aa;
this.ab=ab;
this.something=something
}
item.prototype.bob=2;
item.prototype.method1 = function() {
100 - this.something;
this.something++;
}
Hope this helps
Upvotes: 0
Reputation: 1680
The prototype property is called on the class name and not on the object name. So, if item is an object of class MyClass then you should write:
MyClass.prototype.bob = 2;
You can find more information on the links below:
Upvotes: 0