JavaScript-面试-new与构造函数
2026年10月16日·Admin·2 次浏览
面试题:new 做了什么?手写 new?
new 四步(口述)
- 新建空对象。
- 原型链接:
obj.__proto__ = Constructor.prototype(规范用语为设置[[Prototype]])。 - 执行构造函数,
this指向该对象。 - 若构造函数返回对象,则使用该返回值;否则返回 步骤 1 的对象。
手写伪代码
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
}
与工厂函数
构造函数 + new 用于 instanceof 识别、原型共享方法;工厂函数更灵活但无统一原型链(除非手动返回对象并挂原型)。