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.