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.
const swap = x => x;
– Plauen