← 返回完整题库
JavaScript简单

new 操作符做了什么?

参考答案

new Ctor(...args) 四步:

  1. 创建一个新对象;
  2. 把新对象的 [[Prototype]] 指向 Ctor.prototype(继承原型方法与属性);
  3. 以新对象为 this 执行构造函数(初始化实例属性);
  4. 若构造函数返回对象(引用类型)则返回该对象,否则返回新对象。
function myNew(Ctor, ...args) {
  const obj = Object.create(Ctor.prototype);
  const ret = Ctor.apply(obj, args);
  return ret !== null && (typeof ret === 'object' || typeof ret === 'function') ? ret : obj;
}

注意:箭头函数无 [[Construct]] 不能 new;class 必须 new;new.target 可用于检测构造调用。

本题来自 计算机知识面试题库,共 921 道题。