概念描述
- new Fn() 一个实例
- 定义一个对象 obj ,继承 Fn 的原型属性 Fn.prototype。
- obj 继承 Fn 的实例属性。
- 根据上一步函数执行结果,返回函数最终的结果。
代码实现
import { customCreate } from './007-objectCreate'
export function customNew(Fn: Function, ...args: any[]): object | void {
if (typeof Fn !== 'function') {
console.log('请传入构造函数')
return
}
const obj = customCreate(Fn.prototype)
const result = Fn.apply(obj, args)
return typeof result === 'object' ? result : obj
}
export function Fn(this: any, name: string) {
this.name = name
}
Fn.prototype.say = function () {
console.log('say')
}
const customNewResult = customNew(Fn, 'huen2015')
const customNewResult1 = new Fn('huen2015')
console.log('customNewResult', customNewResult)
console.log('customNewResult1', customNewResult1)