
对象
|
193
你可能还会见到一种稍微古老的克隆方式,使用的是
Object.assign()
方
法。这种
方式与使用展开运算符效果相同。
const
animalCopy = Object.assign({}, animal);
两种方式执行的操作都是浅拷贝(
shallow copy
),不复制对象中值为数组或其他对
象的属性,而是在原对象和新对象之间共用。下面演示这个问题。
const
student = {
firstName: 'Tazie', lastName: 'Yang',
testScores: [78, 88, 94, 91, 88, 96]
};
const
studentCopy = {...student};
//
现在有两个对象共用同一个
testScores
数组
//
修改一些细节便可以看出这一点
//
这只影响副本
studentCopy.firstName = 'Dori';
//
这影响两个对象
studentCopy.testScores[0] = 56;
console.log(student);
// {firstName: "Tazie", lastName: "Yang", testScores: [56, 88, 94, 91, 88, 96]
console.log(studentCopy);
// {firstName: "Dori", lastName: "Yang", testScores: [56, 88, 94, 91, 88, 96]
这种行为算不算问题,要看你想要达到什么样的目的 ...