As shown in the picture above, according to the description, Object.assign() is a shallow copy. Why does changing attribute a not point to the same reference, but b.c points to the same reference?
曾经蜡笔没有小新2017-06-28 09:28:21
var deepCopy = function(src) {
var ret = {}
for (var k in src) {
ret[k] = typeof src[k] ==='object' ? deepCopy(src[k]) : src[k]
}
return ret
}
This method has always been used for deep copy. Object.assgin can only deep copy the first layer. Deep copy is still a shallow copy. Just remember this
漂亮男人2017-06-28 09:28:21
let obj3 = Object.assign({},obj1,{b:Object.assign({},obj1.b)});
let obj4 = JSON.parse(JSON.stringify(obj1));
PHP中文网2017-06-28 09:28:21
Shallow copy: If the attribute element is a complex data type, the inner element copy reference; slice
, concat
, jQury
’s $.extend({},obj)
are all shallow copies;
Click here to learn more