前端嘛 Logo
前端嘛

new 运算符

new 运算符用于创建用户定义的对象类型的实例或具有构造函数的内置对象的实例

中间过程

当使用 new 调用函数时,该函数将被当作构造函数。new 将执行以下操作:

  1. 创建一个空的简单 JS 对象 newInstance,其 [[prototype]] 指向 Object.prototype

  2. 若构造函数的 prototype 是一个对象,那么 newInstance[[prototype]] 改为指向该对象

  3. 使用给定参数执行构造函数,并且构造函数中的所有 this 引用都指向 newInstance

  4. 如果构造函数返回非原始值,那么该返回值成为整个 new 表达式的结果;否则,newInstance 作为 new 表达式的结果返回

手写 new

function myNew(constructor, ...args) {
  if (typeof constructor !== 'function') {
    console.error('Type Error');
    return;
  }
  const newInstance = Object.create(constructor.prototype);
  const result = constructor.apply(newInstance, args);
  if (typeof result === 'object' || typeof result === 'function') {
    return result;
  }
  return newInstance;
}