new 操作符执行时做了什么?
请描述使用 new 关键字调用构造函数时,JavaScript 引擎内部做了哪些步骤。
回答
编译有声
new F() 执行时引擎自动完成以下 4 步:
1. 创建空对象:创建一个新的空对象 obj = {}
2. 链接原型:将对象的 __proto__ 指向构造函数的 prototype 属性
obj.__proto__ = Constructor.prototype;
// 等价于 Object.setPrototypeOf(obj, Constructor.prototype);
3. 绑定 this 并执行:以新对象为 this 执行构造函数
let result = Constructor.call(obj, ...args);
4. 返回结果:
- 若构造函数返回引用类型对象,则返回该对象
- 否则返回新创建的对象
obj
手写实现:
function myNew(Constructor, ...args) {
const obj = Object.create(Constructor.prototype);
const result = Constructor.apply(obj, args);
return (result !== null && typeof result === 'object' || typeof result === 'function')
? result : obj;
}
注意:箭头函数不能作为构造函数(没有 [[Construct]] 内部方法)。