I have the following code:
MyObject.prototype.doIt = function()
{
var a = this.obj1;
var b = this.obj2;
}
How can i swap the values of this.obj1 and this.obj2 so obj1 becomes obj2 and obj2 becomes obj1.
!Note: Have in mind that i am not working with primitive types.
You can swap any number of objects or literals, even of different types, using a simple identity function like this:
var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);
This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments a=b
etc, happen after a
is passed into the function.
Use a temporary variable to hold the contents of one of the objects while swapping:
var tmp = this.obj1;
this.obj1 = this.obj2;
this.obj2 = tmp;
You can swap the properties easily enough:
MyObject.prototype.doIt = function()
{
var a = this.obj1;
var b = this.obj2;
this.obj1 = b;
this.obj2 = a;
}
That obj1
and obj2
are not primitive types is irrelevant. You don't actually need two variables:
MyObject.prototype.doIt = function()
{
var a = this.obj1;
this.obj1 = this.obj2;
this.obj2 = a;
}
However, if any references to this.obj1
or this.obj2
already exist outside this code, they won't be swapped.
In terms of swapping this.obj1
and this.obj2
everywhere (including existing references), I don't think that can be done completely. You could strip out all properties of, say, this.obj1
(saving them somewhere), add in the properties from this.obj2
, and then do the same for this.obj2
. However, you won't be able to swap the prototypes, so objects cannot fundamentally swap identities.
Here is an example with concrete objects, say your original objects are 2 divs, div1 and div2.
To swap them,
var temp1 = div1;
var temp2 = div2;
div1 = temp2;
div2 = temp1;
We can use about the destructing objects, like below code:
let a = 2;
let b = 4;
[a, b] = [b, a];
©2020 All rights reserved.