javascript object copy and assignment

javascript object copy and assignment

var obj = {
    name: 'xiaoming',
    age: 23
};

var newObj = obj;

newObj.name = 'xiaohua';

console.log(obj.name);//'xiaohua'
console.log(newObj.name);//'xiaohua'
 

Above we assign the obj object to the newObj object, thereby changing the name attribute of newObj, but the name attribute of the obj object has also been tampered with. This is because in fact the newObj object obtains only a memory address, not a real copy, so obj The object has been tampered with.

var obj2 = {
    name: 'xiaoming',
    age: 23
};

var newObj2 = Object.assign({}, obj2, {color: 'blue'});

newObj2.name = 'xiaohua';

console.log(obj2.name);//'xiaoming'
console.log(newObj2.name);//'xiaohua'
console.log(newObj2.color);//'blue'
 

Using the Object.assign() method above to make a deep copy of the object can avoid the possibility of tampering with the source object. Because the Object.assign() method can copy any number of enumerable properties of the source object itself to the target object, and then return the target object. However, Object.assign() is only a first-level attribute copy, which is one layer deeper than the shallow copy. When using it, pay attention to this problem.

var obj3 = {
    name: 'xiaoming',
    age: 23
};

var newObj3 = Object.create(obj3);

newObj3.name = 'xiaohua';

console.log(obj3.name);//'xiaoming'
console.log(newObj3.name);//'xiaohua'
 

We can also use the Object.create() method to copy an object. The Object.create() method can create a new object with the specified prototype object and properties.


Learning is a long process, with this person's life, it cannot be done overnight