简体   繁体   中英

javascript - Replace an object with another one

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM