3
var obj1 = New MyObject('Object 1');
var obj2 = New MyObject('Object 2');

var foo = { anObject : obj1 };

foo.anObject = obj2;
console.log(obj1.name);

Naturally, obj1 didn't changed. But how to replace obj1 by obj2 in the whole script assuming I can only access foo ?

4
  • It is not clear what you are asking Commented Aug 24, 2013 at 17:08
  • Your code + use foo.anObject instead of obj1 when referencing it. Commented Aug 24, 2013 at 17:12
  • What for do you want to replace it "in the whole script"? Commented Aug 24, 2013 at 17:14
  • @BillyMoon @Bergi I'd just like a pointer. In C, it should be foo.anObject = &obj1 and then *(foo.anObject) = obj2 Commented Aug 25, 2013 at 0:07

1 Answer 1

5

You should remove all properties in obj1 and then add all properties from obj2. But note that obj1 wont hold the reference to the same object as obj2 but make a new cloned one. Also note the below is shallow cloning with a as target:

var replaceObject = function(a, b) {
    var prop;

    for ( prop in a ) delete a[prop];
    for ( prop in b ) a[prop] = b[prop]; 
};

var a = {a: 1},
    b = {b: 2};

replaceObject(a, b);

a // {b: 2};
// but:
a === b // false
Sign up to request clarification or add additional context in comments.

3 Comments

It's not really the ideal solution, but it's not the ideal case eather. +1 for a simple and clean solution
It works for what I do now, but isn't there a cleaner solution ?
Should the loop body in line 5 be 'a[prop] = b[prop];'?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.