new实现
- 新生成了一个对象
- 新对象隐式原型链接到函数原型
- 调用函数绑定this
- 返回新对象
const myNew = (fn, ...rest) => {
const obj = {}
obj.__proto__ = fn.prototype
const res = fn.apply(obj, rest)
if (res && typeof res === 'object' || typeof obj === 'function') {
return res
}
return obj
}
function Fn(x) {
this.x = x
}
const obj = myNew(Fn, 1)
- 简易版
function myNew(fun) {
let obj = {
__proto__: fun.prototype
}
fun.apply(obj,Array.prototype.slice.call(arguments,1))
return obj
}
以自己现在的努力程度,还没有资格和别人拼天赋

浙公网安备 33010602011771号