zoukankan      html  css  js  c++  java
  • js中new到底做了什么?如何重写new?

    new 构造函数()执行顺序
    1.在堆中开辟对象内存空间, 记为obj
    2.在obj 中添加__proto__属性并指向 构造函数.prototype
    3.将构造函数中的this 指向obj
    4.执行构造函数内语句
        若构造函数中没有reutrn 或return this或基本类型(number、string、boolean、null、undefined)的值,则返回obj在堆中的内存地址;若return 引用类型,则返回值为这个引用类型
    仿写new的行为

    function People(name, age, phone) {
      this.name = name;
      this.age = age;
      this.phone = phone;
      //若构造函数中`没有reutrn 或return this或基本类型`(number、string、boolean、null、undefined)的值,则返回obj在堆中的内存地址;若`return 引用类型`,则返回值为这个引用类型
      // return null;//无影响
      // return {};//返回此对象
      // return function(){};//返回此函数
    }
    
    function _new(...args) {
      let constructor = args[0];//获取构造函数
      let obj = Object.create(constructor.prototype);//创建空对象,并将原型指向构造函数的原型
      let res = constructor.call(obj, ...args.slice(1));//call强行将this指向第一个参数
      if ((typeof res === 'object' || typeof res === 'function') && res != null) {
        return res;
      } else {
        return obj;
      }
    }
    
    let a = _new(People, 'aa', 20, 132456);
    let na = new People('aa', 20, 132456);
    console.log(a, na);
    //运行结果
    People { name: 'aa', age: 20, phone: 132456 }
    People { name: 'aa', age: 20, phone: 132456 }

    ————————————————
    版权声明:本文为CSDN博主「漫疏狂」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/lyt_angularjs/article/details/86623988

  • 相关阅读:
    Windows10安装Oracle19c数据库详细记录(图文详解)
    构建 FTP 文件传输服务器
    构建 Samba 文件共享服务器
    Linux磁盘配额(xfs)
    Linux配置磁盘配额(ext4)
    Linux 制作ISO镜像
    Linux磁盘分区
    用户和文件权限管理命令的使用(实验)
    CentOS7 配置yum源
    VMware CentOS 7 安装(vmware的版本15.5)
  • 原文地址:https://www.cnblogs.com/ygunoil/p/12058622.html
Copyright © 2011-2022 走看看