手写 new 与 instanceof
new和instanceof是 JS 中两块互为镜像的能力:new把一个函数当构造器使用并产生实例,instanceof判断实例与 构造器的关系。它们都依赖原型链。本文实现两个操作并解释清楚每一步的对应规范。
题目描述
- 实现
myNew(Constructor, ...args):等同new Constructor(...args)的行为。 - 实现
myInstanceof(obj, Constructor):等同obj instanceof Constructor,沿原型链查找。
思路分析
new 的四步
ECMAScript 规范中 [[Construct]] 的语义可拆为四步:
- 创建新对象:以
Constructor.prototype为原型新建一个普通对象。 - 绑定并执行:把上一步新对象作为
this,调用构造函数并传入args。 - 判断返回值:如果构造函数返回对象,则
new表达式返回该对象;否则返回第 1 步新建的对象(构造函数显式返回基础类型会被忽略)。 - (规范额外) ES6 的
newTarget、Symbol.species等扩展暂不处理。
关键点:第 1 步要兼容 Constructor.prototype 不是对象的情况(如被改写为 null),此时应回退到 Object.prototype。