- 浅克隆
就是平时的赋值,赋值之后指针指到同一个栈堆,那么我无论改变哪一个值,另外一个赋值或者被赋值的变量都会同时被改变
var num1 = 10;
var num2 = num1;
num2 = 11;
console.log(num1,num2); // 11,11
- 深克隆
就是我虽然继承与你,但是我与你是两个独立的个体,两者任意谁的改变都无法改变对方
其次考虑到适应数据的复杂程度,一般是用递归
const oldObj = {
name:'jack',
age:20,
friend:{
name:'king',
}
}
function deepClone(obj = {}){
if(typeof obj !== 'object' || obj == null){
return obj
}
let result;
if(obj instanceof Array){
result = []
}else{
result = {}
}
// 说一些这里为什么用Reflect.ownKeys()
// 正常来讲直接obj是可以的,但如果你的对象元素里面有Symbol类型,那for of的方法就会遍历不出来
for(let key of Reflect.ownKeys(obj)){
if(obj.hasOwnProperty(key)){
result[key] = deepClone(obj[key])
}
}
return result;
}
// 那么即使当我改变obj的friend元素,也会随之改变
const newObj = deepClone(oldObj)
newObj.friend.name = 'louse';