new 操作符做了什么?
参考答案
new Ctor(...args) 四步:
- 创建一个新对象;
- 把新对象的
[[Prototype]]指向Ctor.prototype(继承原型方法与属性); - 以新对象为
this执行构造函数(初始化实例属性); - 若构造函数返回对象(引用类型)则返回该对象,否则返回新对象。
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 可用于检测构造调用。