• 理解js的new,区分prototype和__proto__


    new

    • 执行过程
      1. 创建一个空对象,作为将要返回的对象实例
      2. 将这个空对象的原型指向构造函数的prototype属性
      3. 将这个空对象赋值给函数内部的this
      4. 执行构造函数内部代码
    function _new(/* 构造函数 */ constructor, /* 构造函数参数 */ params) {
      // 将 arguments 对象转为数组
      var args = [].slice.call(arguments);
      // 取出构造函数
      var constructor = args.shift();
      // 创建一个空对象,继承构造函数的 prototype 属性
      var context = Object.create(constructor.prototype);
      // 执行构造函数
      var result = constructor.apply(context, args);
      // 如果返回结果是对象,就直接返回,否则返回 context 对象
      return (typeof result === 'object' && result != null) ? result : context;
    }

    两个知识点

    1,new.target, 函数内部可以使用它,如果当前函数是使用 new进行调用,那么new.target指向当前函数,否则为undefined

    function NewTargetTest() {
      console.log(new.target === NewTargetTest)
    }
    
    NewTargetTest() // false
    new NewTargetTest() // true

    2,构造函数隐藏的return

    • 构造函数会默认返回构造后的this对象
    • function ReturnTest(name) {
        this.name = name
      }
      
      const returnText = new ReturnTest('wy')
      console.log(returnText.name) // wy
    • 将上面的代码稍加改造,显示的返回一个空对象{},此时会覆盖默认返回的this对象

    • function ReturnTest(name) {
        this.name = name
        return {}
      }
      
      const returnText = new ReturnTest('wy')
      console.log(returnText.name) // undefined
    • 将上面的代码稍加改造,显示的返回一个基本类型的数据,此时将不会影响构造函数返回的this对象
    • function ReturnTest(name) {
        this.name = name
        return 'test'
      }
      
      const returnText = new ReturnTest('wy')
      console.log(returnText.name) // wy

    prototype与__proto__

    构造函数访问原型时,通常通过prototype来访问,例如我们往原型上添加方法

    Person.prototype.getName = function() {}

    当new出来的实例访问原型时,在一些支持的浏览器中

    function Person() {}

    var p1 = new Person();

    p1.__proto__ === Person.prototype   // true

    结论:prototype是作为构造函数去访问原型,而__proto__是作为实例去访问原型。当自身身份不一样,即使一个方法同时调用两者时,访问到的可能是不同的原型。

  • 相关阅读:
    MFC
    驱动学习
    Ubuntu下为Apache简单配置SSL的方法(HTTPS的实现)
    在linux下helloworld的C程序
    swift安装,linux
    gcc,cc,g++,CC的区别
    ldconfig与 /etc/ld.so.conf
    ubuntu16.04,mysql5.7重启不成功。Restarting mysql (via systemctl): mysql.serviceJob for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service"
    linux .o,.a,.so文件
    zipgateway-2-61-0的安装
  • 原文地址:https://www.cnblogs.com/hsmWorld/p/12803039.html
Copyright © 2020-2023  润新知