Change current object in its prototype

163 views Asked by At

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"
1

There are 1 answers

0
Yuriy Galanter On BEST ANSWER

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.