乐趣区

关于javascript:JavaScript深拷贝

const oldObj = {
  name: 'tao',
  age: 20,
  color: ['orange', 'green', 'blue'],
  friend: {name: 'gua'},
  fn: function(){console.log(1)
  }
}
function deepClone(obj) {
  // 判断不是数组或对象
  if(typeof obj !== 'object' || obj === null) {return obj}
  let res
  if(obj instanceof Array) {res = []
  } else {res = {}
  }
  for(let k in obj) {
    // 过滤掉 obj 原型上的属性
    if(obj.hasOwnProperty(k)) {res[k] = deepClone(obj[k])
    }
  }
  return res
}
const newObj = deepClone(oldObj)
newObj.friend.name = 'taotao'
console.log(oldObj, newObj)
newObj.fn()
退出移动版