Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why properties of function not overrided to default when new instance of object created?

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?????
like image 402
IvanV Avatar asked Nov 22 '25 16:11

IvanV


1 Answers

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);
}
like image 133
JohanP Avatar answered Nov 24 '25 07:11

JohanP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!