示例工程 05-objects-prototypes-class
05-objects-prototypes-class/01-manual-new/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— 手写 new:四步拆开
// 目标不是替代 new,而是把 [[Construct]] 的行为显式化。
export function myNew(Ctor, ...args) {
if (typeof Ctor !== 'function') {
throw new TypeError('myNew 的第一个参数必须是函数');
}
// 第 1、2 步:创建对象,并把原型指向 Ctor.prototype(非对象时回退到 Object.prototype)
const proto = Ctor.prototype;
const instance = Object.create(
proto !== null && (typeof proto === 'object' || typeof proto === 'function')
? proto
: Object.prototype,
);
// 第 3 步:以新对象为 this 执行构造函数
const result = Ctor.apply(instance, args);
// 第 4 步:构造函数返回对象则用它,否则用新对象
return result !== null && (typeof result === 'object' || typeof result === 'function')
? result
: instance;
}
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return `hi ${this.name}`;
};
function ReturnsObject() {
this.discarded = true;
return { replaced: true };
}
function ReturnsPrimitive() {
this.kept = true;
return 42;
}
export function run(log = console.log) {
const p = myNew(Person, 'Ada');
const objOverride = myNew(ReturnsObject);
const primitiveIgnored = myNew(ReturnsPrimitive);
const rows = [
['实例字段 name', p.name],
['原型方法 greet()', p.greet()],
['原型是否等于 Person.prototype', String(Object.getPrototypeOf(p) === Person.prototype)],
['instanceof Person', String(p instanceof Person)],
['构造函数返回对象:被采用', JSON.stringify(objOverride)],
['构造函数返回原始值:被忽略', JSON.stringify(primitiveIgnored)],
];
log('场景 => 结果');
for (const [label, value] of rows) log(`${label} => ${value}`);
log('-'.repeat(50));
log('要点:new = 建对象 + 挂原型 + 以它为 this 调用 + 按返回值决定最终结果。');
return rows;
}