8

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.

5 Answers 5

17

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.

1
  • using this but like: const swap = x => x; Apr 8, 2022 at 1:29
5

We can use about the destructing objects, like below code:

let a = 2;
let b = 4;
[a, b] = [b, a];
4

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;
2

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.

2
  • In fact, you could swap prototype with the use of Object.getPrototypeOf() and Object.setPrototypeOf(), but MDN strongly warn us it's a really bad idea for the application performance. Aug 14, 2017 at 16:31
  • @FélixBrunet - Hadn't thought about that. I guess it is possible to implement something like Smalltalk's become: method. Cool!
    – Ted Hopp
    Aug 14, 2017 at 16:48
0

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.