js模拟构造函数的实现过程

joken-前端工程师 / 2025-04-15 / 原文

下面是 TypeScript 版本的 myNew 函数实现:

function myNew<T>(constructor: new (...args: any[]) => T, ...args: any[]): T {
    // 创建一个新对象,原型指向构造函数的 prototype
    const obj = Object.create(constructor.prototype);

    // 调用构造函数,绑定 this 为新对象
    const res = constructor.apply(obj, args);

    // 如果构造函数返回一个对象,返回该对象;否则返回新创建的对象
    return (typeof res === 'object' && res !== null) ? res : obj;
}

// 示例构造函数
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

// 使用自定义的 myNew 函数创建实例
const person1 = myNew(Person, 'Alice', 30);
const person2 = myNew(Person, 'Bob', 25);

// 输出对象的属性
console.log(person1.name); // Alice
console.log(person1.age);  // 30
console.log(person2.name); // Bob
console.log(person2.age);  // 25

代码解析

  1. 泛型类型参数

    function myNew<T>(constructor: new (...args: any[]) => T, ...args: any[]): T {
    
    • T 是一个泛型类型参数,表示构造函数返回的实例类型。
    • constructor 的类型为 new (...args: any[]) => T,这表示它是一个构造函数,接受任意数量的参数并返回类型 T 的实例。
  2. 创建对象

    const obj = Object.create(constructor.prototype);
    
    • 使用 Object.create 创建新对象,并将其原型指向构造函数的 prototype
  3. 调用构造函数

    const res = constructor.apply(obj, args);
    
    • 使用 apply 方法调用构造函数,将 this 绑定到新对象 obj
  4. 返回结果

    return (typeof res === 'object' && res !== null) ? res : obj;
    
    • 根据构造函数的返回值决定返回哪个对象。

示例构造函数

  • 使用 class 关键字定义 Person 构造函数,并添加类型注解。