Question

How to change an object itself, the pointer to object, create another object.

Array.prototype.change=function(b){
    // this=b; //does not work
}

a=[1,2,3];
b=[3,2,1];

a.change(b);

console.log(a); // Should be [3,2,1]

Another example:

String.prototype.double=function(){
    //this+=this; //like str+=str
}

str="hello";

str.double();

console.log(str); // echo "hellohello"
Was it helpful?

Solution

You can define your prototype like this:

Array.prototype.change = function (b) {
   this.length = 0;
   this.push.apply(this, b);
}

Internally it will clear existing data and add data from array in parameter.

This will not make Array a exactly equal Array b (they will still be different objects with different references and a == b would be false) but data in both will be the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top