- 创建一个新对象base,将base的原型链设置为构造函数的原型
- new构造函数,构造函数的this指向新对象,可以为新对象添加实例属性
- 执行构造函数,如果构造函数自己有引用类型的返回值ret,就用ret, 否则用base
const isValidRet = v => v !== null && (typeof v === "object" || typeof v === "function")
const objectFactory = function (Ctor, ...args) {
if (typeof Ctor !== 'function') throw 'Ctor must be a function'
const base = Object.create(Ctor.prototype)
const ret = Ctor.apply(base, args)
return isValidRet(ret) ? ret : base
}
const F = function (a, b) {
this.a = a
this.b = b
return null
}
console.dir(objectFactory(F, 1, 2));
console.dir(objectFactory());