675 对象的引用-浅拷贝-深拷贝

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

  <!-- 1.对象的引用赋值 -->
  <script>
    // 对象是引用类型
    // const info = {name: "why", age: 18};
    // const obj = info;
    // info.name = "kobe";
    // console.log(obj.name);
  </script>

  <!-- 2.对象的浅拷贝 -->
  <script>
    const info = { name: "why", age: 18, friend: { name: "kobe" } };
    // const obj = Object.assign({}, info);

    // lodash
    const obj = _.clone(info);

    // info.name = "kobe";
    // console.log(obj.name);

    // info.friend.name = "james";
    // console.log(obj.friend.name);
  </script>

  <!-- 3.对象的深拷贝 -->
  <script>
    // _.cloneDeep(info)

    // const info = {name: "why", age: 18, friend: {name: "kobe"}};
    // const obj = JSON.parse(JSON.stringify(info)); // 生成一个新的对象
    // info.friend.name = "james";
    // console.log(obj.friend.name);
  </script>

  <!-- 我的补充 -->
  <script>
    const info2 = { name: "why", age: 18, friend: { name: "kobe" } };
    const obj2 = Object.assign({}, info2)
    console.log(info2)
    console.log(obj2)
    console.log(obj2 == info2) // false

    info2.name = '哈哈哈'
    console.log(info2.name)
    console.log(obj2.name)

    info2.friend.name = '呵呵'
    console.log(info2.friend.name)
    console.log(obj2.friend.name)
    console.log(obj2.friend === info2.friend) // true

    console.log('----------------')

    const info3 = {
      name: "why",
      age: 18,
      friend: { name: "kobe" },
      reg: /\d/,
      fn: function fn() {
        console.log(111)
      },
      date1: new Date()
    };

    const obj3 = JSON.parse(JSON.stringify(info3))
    console.log(info3)
    console.log(obj3)
    console.log(obj3 == info3) // false
    console.log(obj3.friend == info3.friend) // false
  </script>

</body>

</html>

675  对象的引用-浅拷贝-深拷贝

上一篇:JavaScript 使用new关键字调用函数


下一篇:lucene创建索引简单示例