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.

2 Answers 2

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.

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

Comments

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.

1 Comment

thanks for reminding... but just to add sth I have seen from another post, stackoverflow.com/questions/7486085/… This method only works for number and strings within array, BUT not object arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.