1,创建一个空对象
2,链接到构造函数的原型
3,绑定this到该对象
4,返回新对象
function newF(FN, ...args) {
var obj = {}
obj.__proto__ = FN.prototype
var result = FN.apply(obj, args)
return typeof result === "object" ? result : obj
}
function Person(name, age) {
this.name = name
this.age = age
}
var p = newF(Person, "bobo", 23)
console.log(p)
console.log(p instanceof Person)
使用Object.create
简化写法
function newF(FN, ...args) {
var obj = Object.create(FN.prototype)
var result = FN.apply(obj, args)
return typeof result === "object" ? result : obj
}