zoukankan      html  css  js  c++  java
  • 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>
    

  • 相关阅读:
    第二次作业
    《自动化技术中的进给电气传动》读书笔记1.1-1.2
    证券投资分析
    微信官方文档概述
    联想拯救者Y7000电池无法充电问题
    Ubuntu用户权限管理
    证券市场基础知识
    Markdown All in One使用教程
    Markdown学习笔记
    第九周
  • 原文地址:https://www.cnblogs.com/jianjie/p/14798677.html
Copyright © 2011-2022 走看看