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?

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;} Commented Mar 15, 2016 at 2:38
  • In a case like this you need to initialize the property in the constructor (function Test() {this.item = [];}). See stackoverflow.com/a/16751343/560114 and also bennadel.com/blog/…. Commented Mar 15, 2016 at 2: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). Commented Mar 15, 2016 at 2:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.