Reputation: 131
i've a nice problem here. I need to understand this
Foo = function(){
};
Foo.prototype = {
buttons: new Array(),
index:'',
add: function(value)
{
this.buttons.push(value);
},
clear:function(){
this.buttons=new Array();
},
count:function(){
return(this.buttons.length);
},
setIndex:function(index){
this.index;
},
getIndex:function(index){
return this.index;
}
};
var A= new Foo();
var B= new Foo();
A.add('toto');
B.add('tata');
A.setIndex(8);
B.setIndex(44);
alert(A.count()+"---"+A.getIndex());
That code gives me : "2---8" !!
So A.count() returns me A.count() + B.count(). Same with B.count() !!
Can anyone explain me this, already had this problem ? How to do ? i simply need the array "buttons" to be unique, proper to each object.
Upvotes: 2
Views: 95
Reputation: 276306
This is not how prototypical inheritance works, A
and B
have the same prototype, this means they have the same buttons
array.
In JavaScript inheritance is prototypical, what you'd like is for each "Foo" object to have a separate buttons array but you're adding it to Foo
's prototype so it's shared across all of its instances.
You can change this:
var Foo = function(){
};
To
Foo = function(){
this.buttons = []; //add an empty buttons array to every foo element.
};
That would make it work, another alternative would be to call the clear
method first, it would instantiate a new buttons
array.
Note that prototypical inheritance is mostly about sharing functionality and not properties. You'd like each of your Foo
instances to have the same functionality but to each have their own buttons
array.
Some resources to help you:
Here is a good tutorial about how the prototypical chain works on MDN
Here is Addy Osmani's (Google) chapter about the constructor pattern from his JavaScript patterns book
Some other tips on your code:
The syntax new Array()
can be shortened to []
. In setIndex
you're not actually assigning the index to anything. index
is probably better declared in the constructor function of Foo
as well.
Note that when you're setting an object's property where such a property exists on the prototype chain it creates a new property on the object rather than modify that property on the prototype.
Upvotes: 5
Reputation: 10833
When you define the variable in the prototype it is shared across all instances of Foo
. You have to define the behaviour in your object (function) Foo
to have an instance of the array for each instance of Foo
.
Upvotes: 1