new一个对象的过程是什么,手写代码表示

new 一个对象的过程

- 创建一个空对象 obj,继承构造函数的原型

- 执行构造函数(将 obj 作为 this)

- 返回 obj

/**
 * @description 实现 new
 */

export function customNew<T>(constructor: Function, ...args: any[]): T {
    // 1. 创建一个空对象,继承 constructor 的原型
    const obj = Object.create(constructor.prototype)
    // 2. 将 obj 作为 this ,执行 constructor ,传入参数
    constructor.apply(obj, args)
    // 3. 返回 obj
    return obj
}

class Foo {
    // 属性
    name: string
    city: string
    n: number

    constructor(name: string, n: number) {
        this.name = name
        this.city = '北京'
        this.n = n
    }

    getName() {
        return this.name
    }
}

const f = customNew<Foo>(Foo, '双越', 100)
console.info(f)
console.info(f.getName())

Object.create 和 {} 的区别

{}  创建空对象,原型指向 Object.prototype

`Object.create`  创建一个空对象,原型指向传入的参数

猜你喜欢

转载自blog.csdn.net/m0_38066007/article/details/124951051