1

I am new to Javascript and now suffer from one problem on Array.push and this in prototype.

Here is my code:

function Ball(array) {
    this.array = array; 
}

Ball.prototype.allArray = []; // this is a property shared among ALL Ball object, though here I just create one object... 
Ball.prototype.addArray = function() {
    this.allArray.push(12); 
}

Ball.prototype.changeArray = function() {
    var array = this.array; 
    var allArray = this.allArray; 

    for (var i = 0; i < allArray.length; i++) {
        array.push(allArray[i]); 
    }
    // Array.prototype.push.apply(array, allArray); // same result as above 

    alert(array.length); // 3 Expected

    /*         PROBLEM          */
    alert(this.array.length); // 3, expected 2 Why 3? We just change array NOT this.array... 
}

var ball = new Ball([123, 198]); 
ball.addArray(); 
ball.changeArray(); 

As stated in the above code, I've a problem on why this.array.length = 3, but not 2.

In the changeArray method, I've been changing only array values, not array.length. That means the value of this.array should remain unchanged. Therefore, this.array.length should be 2.

Are there any things wrong in my thinking? In addition, how can I get this.array.length = 2; while continue to get array.length = 3?

P.S. You may also take a look at this running code in JSFiddle.

Megan Caithlyn
  • 374
  • 2
  • 11
  • 33
CHANist
  • 1,302
  • 11
  • 36

2 Answers2

2

this.array; //inside changeArray() points to the same array which you passed to new Ball([123, 198]);

var array = this.array; // this makes array point to same array. So changes to array will also change your array.

Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79
1

With

 var array = this.array; 
 var allArray = this.allArray; 

you effectively set pointers to the properties of the this object. So, everything you seemingly do with array you actually do with this.array.

If you want to work on a copy of this.array you should do

var array=this.array.slice(0);

instead. You should be aware though that even this approach will generate the new array-elements only on one level. If you were working with an array of arrays then the inside arrays (or any other objects) will again only be pointers to the original ones.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • thanks for reminding... but just to add sth I have seen from another post, http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript This method only works for number and strings within array, BUT not object arrays. – CHANist Aug 20 '15 at 05:03