- 新生成了一个对象
- 新对象隐式原型链接到函数原型
- 调用函数绑定this
- 返回新对象
function myNew(fun){
var res = {}
if(fun.prototype !== null){
res.__proto__ = fun.prototype
}
var ret = fun.apply(res,Array.prototype.slice.call(arguments,1))
// 防止构造函数主动return function或object
if((typeof ret === 'object' || typeof ret === 'function') && ret !== null){
return ret
}
return res
}
- 简易版
function myNew(fun) {
let obj = {
__proto__: fun.prototype
}
fun.apply(obj,Array.prototype.slice.call(arguments,1))
return obj
}