new 构造函数 的过程做了什么

147 阅读1分钟

我们经常使用new调用构造函数得到一个实例,那么在new的过程中它做了些什么呢,这里总结一下自己对new过程的理解:

大致分为四步:

  1. 创建对象
  2. 链接原型
  3. 改变this指向,并执行构造函数
  4. 返回对象
function MyNew(fn, ...arg) {
      const obj = Object.create(fn.prototype)//将1、2步骤合并
      // 1、创建对象
      // const obj = {};
      // 2、链接原型
      // obj.__proto__ = fn.prototype;
      // 3、改变this指向,执行构造函数,得到结果
      const result = fn.call(obj, ...arg);
      // 如果构造函数中有返回值,且返回值不是基本数据类型,就将它返回;
      const basicType = ['String', 'Number', 'Boolean', 'Null', 'Undefined'];
      const type = Object.prototype.toString.call(result);// 获取数据类型
      const str = type.substring(8, type.length - 1);
      if (!basicType.includes(str)) return result;
      // 4、返回对象
      return obj;
    }

例子:

function Parent(name) {
      this.name = name;
    }
    Parent.prototype.say = function () {
      console.log('哈喽');
    }

    let p = new Parent('张三');
    let p1 = MyNew(Parent, '张三');
    //p和p1的结果是一样的

注意:如果构造函数中有返回值,且返回值不是基本数据类型,那么new创建的结果就是构造函数的返回值