new 操作符做了什么?
创建一个新对象:空的普通对象 {}。
设置原型:将新对象的 [[Prototype]](即 proto)指向构造函数的 prototype 属性。
绑定 this:将构造函数的 this 指向这个新对象,并执行构造函数体。
返回对象: 如果构造函数返回一个对象,则返回该对象; 否则,返回新创建的实例对象。
function myNew(Constructor, ...args) {
// 边界检查:Constructor 必须是函数
if (typeof Constructor !== 'function') {
throw new TypeError('Constructor is not a function');
}
// 1. 创建一个空对象
const obj = Object.create(Constructor.prototype);
// 2. 执行构造函数,绑定 this
const result = Constructor.apply(obj, args);
// 3. 返回对象:优先返回构造函数返回的对象(如果是对象)
if (result !== null && (typeof result === 'object' || typeof result === 'function')) {
return result;
}
// 否则返回新创建的对象
return obj;
}