0

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"
holden321
  • 1,166
  • 2
  • 17
  • 32
  • 1
    You want to [return the reversed array](http://jsfiddle.net/davidThomas/DSeUf/1/), or [return a new variable entirely](http://jsfiddle.net/davidThomas/DSeUf/) (as denoted by `b` in your question)? Either way though: `return` whatever (though you may have to pass the 'other' variable in, first. Which makes it a little pointless). – David Thomas Sep 12 '13 at 21:56
  • You can't assign `this`, just `return` something and assign the result to a variable. – elclanrs Sep 12 '13 at 21:57
  • You cannot assign to variables outside of your scope, nor can you assign to `this`. You only can modify the object you have. – Bergi Sep 12 '13 at 21:58
  • possible duplicate of [Assign object to "this"](http://stackoverflow.com/questions/15598549/assign-object-to-this) – Bergi Sep 12 '13 at 21:59
  • David Thomas, I don't want to return anything. I want to change current object so that a and b were the same object or at least a will be a new object (like this=[]) – holden321 Sep 12 '13 at 22:06
  • 1
    Erm... but if you want them to be the same object, what's wrong with `a = b` then? And if you want `a` to become clone of `b`, do [just that](http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object). – raina77ow Sep 12 '13 at 22:08
  • Yeah. You're adding an unnecessary step. Unless you're trying to do something more complex, the correct answer is a = b. – mikekavouras Sep 12 '13 at 22:15
  • I want to do it inside a prototype. I have an academic task. The arrays are just examples. See another example with string. – holden321 Sep 13 '13 at 05:29
  • Just assign a newly created object to the same variable like `str = str.double()`. – Bart Sep 13 '13 at 07:05

1 Answers1

1

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.

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136