- 创建一个新的空对象
- 将新对象的
__proto__
指向构造函数的prototype
- 将构造函数中
this
指向新对象(借助 call/apply) - 判断构造函数的返回值
- 设置了返回值:
若返回值为引用值,则返回引用值
若返回值为原始数据,则返回新对象 - 未设置返回值:返回新对象
- 设置了返回值:
模拟实现
function newFn (Fn, params) {
// 创建一个新的空对象 instance
const instance = {
};
// 将 instance 的 __proto__ 属性指向构造函数的原型(Fn.prototype)
instance.__proto__ = Fn.prototype;
// 以 instance 来调用执行构造函数(借助 call/apply)
const result = Fn.apply(instance, params);
// 判断构造函数的返回值,返回 instance 或函数返回值(当构造函数返回值为 object 时)
return (result && (typeof result === 'object' || typeof result === 'function')) ? result : instance;
}