Please explain why new instance obj2 of function foo still have element in items array? Why it's not overrided when I call new foo()?
var foo = function() {}
foo.prototype = {
items : [],
addItem : function()
{
this.items.push("item");
}
}
var obj = new foo();
obj.addItem();
console.log(obj.items.length); //1 as expected
var obj2 = new foo();
console.log(obj2.items.length); // 1, why not 0?????
You've added it to the prototype which means all instances will share it. You want a new items array for every instance of Foo. To achieve this, you need to move that out of the prototype and into the body of your function. You will attach it to this.
function Foo() {
this.items = [];
}
Foo.prototype.addItem = function(item) {
this.items.push(item);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With