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
?
PS You may also take a look at this running code in JSFiddle .
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.