1

I have this script below, which is triggered on button click:

<button>Click</button>

<script>
  var test = function(){};
  test.prototype = {
    item:[]
  };

  $(document).ready(function(){
    $("button").on('click',function(){
      var t = new test();
      t.item.push(1);
      console.log(t.item);//[1],[1,1],[1,1,1]
    });
  })
  </script>

Why is it that t.item's value always loops, instead of generating a new one with none value?

GAntoine
  • 1,265
  • 2
  • 16
  • 28
J.Tang
  • 13
  • 3
  • I think you want item as a property, and 'push' in your method (prototype). So `var test = function(){this.item=[];}` and `test.prototype.doSomething = function(i){ this.item.push(i); return this.item;}` – oortCloud Mar 15 '16 at 02:38
  • In a case like this you need to initialize the property in the constructor (`function Test() {this.item = [];}`). See http://stackoverflow.com/a/16751343/560114 and also http://www.bennadel.com/blog/1566-using-super-constructors-is-critical-in-prototypal-inheritance-in-javascript.htm. – Matt Browne Mar 15 '16 at 02:38
  • Personally I declare *all* data properties in the constructor rather than in the prototype, in order to avoid this issue. Though technically it's only necessary to do it for non-primitive types (i.e. objects and arrays). – Matt Browne Mar 15 '16 at 02:40

1 Answers1

1

Because t.item is being a refference to test.prototype.item.

So new objects will inherit the item array.

You can avoid by doing

var test = function(){this.item=[];};

That will create a new array on the object itself, instead of using the same array on the prototype for all instances.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
iovoid
  • 193
  • 2
  • 11