new操作符做了以下工作

手写new操作符(适用于Class类和Function构造函数)

 1function mynew<Func extends new (...args: any[]) => any>(Func: Func, ...args: any[]): InstanceType<Func> {
 2  
 3  const obj = Object.create(Func.prototype);
 4  
 5  
 6  const res = Func.apply(obj, args);
 7
 8  
 9  return (typeof res === 'object' && res !== null) ? res : obj;
10}
11
12
13class MyClass {
14  constructor(public name: string) {}
15}
16
17const instance = mynew(MyClass, "Alice");
18console.log(instance.name); 
  1. 使用 Object.create()

    • Object.create(Func.prototype) 创建了一个新的空对象,并将其原型设置为 Func.prototype。这等同于手动设置 __proto__ 的效果,但更符合标准和规范。
  2. 泛型类型参数

    • Func extends new (...args: any[]) => any 定义了 Func 是一个构造函数类型,它接受任意数量的参数并返回任意类型的实例。
    • InstanceType 是 TypeScript 中的一个类型操作符,用于从一个构造函数类型中提取其实例类型
    • InstanceType<Func> 表示 Func 构造函数所创建的实例类型,这样可以确保返回值的类型正确性。
  3. 检查返回值

    • typeof res === 'object' && res !== null 检查构造函数返回的 res 是否是一个非空对象。如果是,则返回 res;否则返回新创建的对象 obj
    • 构造函数中返回一个原始值,则该原始值不会被返回,不起作用;若构造函数返回值为对象,则这个返回值会被正常返回。
个人笔记记录 2021 ~ 2025