new - 创建一个实例

54 阅读1分钟

概念描述

  • new Fn() 一个实例
  • 定义一个对象 obj ,继承 Fn 的原型属性 Fn.prototype。
  • obj 继承 Fn 的实例属性。
  • 根据上一步函数执行结果,返回函数最终的结果。

代码实现

/**
* @description: new 
* @author: huen2015
*/
import { customCreate } from './007-objectCreate'

export function customNew(Fn: Function, ...args: any[]): object | void {
    if (typeof Fn !== 'function') {
        console.log('请传入构造函数')
        return
    }
    // 定义一个对象 obj ,继承 Fn 的原型属性 Fn.prototype。
    // const obj = Object.create(Fn.prototype)
    const obj = customCreate(Fn.prototype)
    // obj 继承 Fn 的实例属性
    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')
// @ts-ignore
const customNewResult1 = new Fn('huen2015')
console.log('customNewResult', customNewResult)
console.log('customNewResult1', customNewResult1)

代码演示仓库