B对象复制了A对象,当修改A对象时,看B对象是否会发生变化,如果B对象也跟着变了,说明这是浅拷贝。,如果B对象没变,那就是深拷贝。
浅拷贝
- 普通函数
function shallowClone (source){
if(!source || typeof source != 'object'){
throw new Error ('error');
}
let targetObj = source.constructor === Array ? [] : {};
for(let keys in source) {
if(source.hasOwnProperty(keys)){
targetObj[keys] = source[keys];
}
}
return targetObj
}
let obj ={
name:"zhang",
age:16,
sex:"men",
friends:["wang","zhang","li"]
}
let obj2 = shallowClone(obj)
obj2.friends.push("tan")
console.log(obj2) //{name: "zhang", age: 16, sex: "men", friends: ["wang", "zhang", "li", "tan"]}
console.log(obj) //{name: "zhang", age: 16, sex: "men", friends: ["wang", "zhang", "li", "tan"]}
- 使用ES6的Object.assign浅拷贝
let obj ={
name:"zhang",
age:16,
sex:"men",
friends:["wang","zhang","li"]
}
let obj2 = Object.assign({}, obj);
obj2.friends.push("tan")
console.log(obj)
console.log(obj2)
深拷贝
let obj1 = {
arr: [1, 2, 3],
obj: {
key: 'value'
},
func:function(){
return 1;
}
};
let tar={}
function copy(selfObj,targetObj ={}){
for (let name in selfObj){
if(typeof selfObj[name] === "object"){ // 判断对象下的属性是对象(数组)还是普通value
targetObj[name] = (selfObj[name].constructor == Array) ? []:{};// 判断是数组还是对象
copy(selfObj[name],targetObj[name]); // 递归调用克隆对象下的对象
}else{
targetObj[name] = selfObj[name] // 如果不是对象,直接把值赋给目标对象。
}
}
return targetObj
}
obj2 = copy(obj1)
console.log(obj2 == obj1)
网友评论