理解js中的浅拷贝和深拷贝

2019-09-25  本文已影响0人  不懂代码的小白
JavaScript的变量类型
基本类型
引用类型

浅拷贝

深拷贝

浅拷贝和深拷贝的区别

浅拷贝实现

Object.assign()
let obj1 = {
  name: '张三',
  age: 18,
  child: {
    name: '李四',
    age: 22
  }
}
let obj2 = Object.assign({}, obj1)
obj2.age = 50
obj2.child.age = 888
console.log(obj1)
console.log(obj2)
$ node index.js
{ name: '张三', age: 18, child: { name: '李四', age: 888 } }
{ name: '张三', age: 50, child: { name: '李四', age: 888 } }
自定义方法 shadowCopy()
function shadowCopy(obj) {
 let newObj = {}
 for (let k in obj) {
   newObj[k] = obj[k]
 }
 return newObj
}
let obj1 = {
 name: '张三',
 age: 18,
 child: {
   name: '李四',
   age: 22
 }
}
let obj2 = shadowCopy(obj1)
obj2.age = 50
obj2.child.age = 888
console.log(obj1)
console.log(obj2)
$ node index.js
{ name: '张三', age: 18, child: { name: '李四', age: 888 } }
{ name: '张三', age: 50, child: { name: '李四', age: 888 } }

深拷贝实现

JSON.paerse() JSON.stringify()
缺点
let obj1 = {
  name: '张三',
  age: 18,
  child: {
    name: '李四',
    age: 22
  },
  func() {
    console.log('hello:' + this.name)
  }
}
let obj2 = JSON.parse(JSON.stringify(obj1))
obj2.age = 50
obj2.child.age = 888
console.log(obj1)
console.log(obj1.func)
console.log('------------------------')
console.log(obj2)
console.log(obj2.func)
$ node index.js
{ name: '张三',
  age: 18,
  child: { name: '李四', age: 22 },
  func: [Function: func] }
[Function: func]
------------------------
{ name: '张三', age: 50, child: { name: '李四', age: 888 } }
undefined
自定义方法 deepCopy()
function deepCopy(obj) {
  let result = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (typeof obj[key] === 'object' && obj[key]!==null) {
        result[key] = deepCopy(obj[key]);   //递归复制
      } else {
        result[key] = obj[key];
      }
    }
  }
  return result;
}
let obj1 = {
  name: '张三',
  age: 18,
  child: {
    name: '李四',
    age: 22
  },
  func() {
    console.log('hello:' + this.name)
  }
}
let obj2 = deepCopy(obj1)
obj2.name = '陈二'
obj2.age = 50
obj2.child.name = 'bgbhjbj'
obj2.child.age = 888
console.log(obj1)
console.log(obj1.func)
console.log('------------------------')
console.log(obj2)
console.log(obj2.func)
$ node index.js
{ name: '张三',
  age: 18,
  child: { name: '李四', age: 22 },
  func: [Function: func] }
[Function: func]
------------------------
{ name: '陈二',
  age: 50,
  child: { name: 'bgbhjbj', age: 888 },
  func: [Function: func] }
[Function: func]
上一篇下一篇

猜你喜欢

热点阅读