new 实例化对象过程

  1. 创建一个新的空对象
  2. 将新对象的 __proto__ 指向构造函数的prototype
  3. 将构造函数中this指向新对象(借助 call/apply)
  4. 判断构造函数的返回值
    1. 设置了返回值:
      若返回值为引用值,则返回引用值
      若返回值为原始数据,则返回新对象
    2. 未设置返回值:返回新对象

模拟实现

function newFn (Fn, params) {
    
    
    // 创建一个新的空对象 instance
    const instance = {
    
    };

    // 将 instance 的 __proto__ 属性指向构造函数的原型(Fn.prototype)
    instance.__proto__ = Fn.prototype;

    // 以 instance 来调用执行构造函数(借助 call/apply)
    const result = Fn.apply(instance, params);

    // 判断构造函数的返回值,返回 instance 或函数返回值(当构造函数返回值为 object 时)
    return (result && (typeof result === 'object' || typeof result === 'function')) ? result : instance;
}

猜你喜欢

转载自blog.csdn.net/weixin_44257930/article/details/108539141