Blake
Blake

Reputation: 7547

How to reference an object instead of copy it?

How to reference an object instead of copy it? As shown in the code below, obviously o2 remains unchange when o = 1 is called. What if I want to make o2 change when o is changed, how to do it?

var o = { 
  a: {
    b:2
  }
}; 
// 2 objects are created. One is referenced by the other as one of its property.
// The other is referenced by virtue of being assigned to the 'o' variable.
// Obviously, none can be garbage-collected


var o2 = o; // the 'o2' variable is the second thing that 
            // has a reference to the object
o = 1;      // now, the object that was originally in 'o' has a unique reference
            // embodied by the 'o2' variable

Upvotes: 2

Views: 86

Answers (4)

Abs
Abs

Reputation: 3962

JS primitive integers and strings are passed by value whereas objects are passed by reference.

To achieve what you want you could use a closure:

var o = { 
  a: {
    b:2
  }
}; 

var o2 = function() { return o; }; 
o = 1; 
console.log(o2());

Upvotes: 1

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12892

You can do it with the help of the closures:

function Closure() {
    var o = { 
      a: {
        b:2
      }
    }; 

    this.getO = function () {
        return o;
    };
}

var closure = new Closure(),
    newO = closure.getO();
newO.a = 111;

console.dir(closure.getO());

Upvotes: 2

manish
manish

Reputation: 956

In javascript,variables always have reference to the object. They are never copied.

Here's what you doing:

var o = { 
  a: {
    b:2
  }
}; 

Created a new object and 'o' is referencing to that object.

var o2 = o;

Now both o and o2 are referencing to same object that you created initially.

o = 1;

Now here's the tricky part. Here you are assigning Number 1 to 'o' variable, which was previously referring to the object you created. 'o2' is still referring to that object. But now, the 'o' is no longer referring to the object,it is coerced to Number type. (in simple terms, coercion means type conversion)

Upvotes: 1

orlland
orlland

Reputation: 1266

o is not the object but just a reference. You just reassigned it to 1 but you're not really overwriting or changing the previously referenced object of o.

Upvotes: 1

Related Questions