Skip to content

myNew

手动实现的 new 操作符,用于理解构造函数的实例化过程。

函数签名

typescript
function myNew<T>(
  constructor: new (...args: any[]) => T,
  ...args: any[]
): T

参数

参数名类型必填说明
constructornew (...args: any[]) => T构造函数
...argsany[]传递给构造函数的参数

返回值

类型说明
T构造函数的实例对象

工作原理

  1. 创建新对象

    • 创建空对象:{}
    • 设置对象的原型为构造函数的 prototype:Object.create(constructor.prototype)
  2. 执行构造函数

    • 将构造函数作为普通函数调用
    • 使用 apply 绑定新对象为 this
    • 传入参数:constructor.apply(obj, args)
  3. 处理返回值

    • 如果构造函数返回对象:使用返回的对象
    • 如果构造函数返回基本类型或 undefined:使用创建的新对象
  4. 返回最终对象

new 操作符的工作原理

  1. 创建新对象
  2. 设置原型链
  3. 绑定 this 并执行构造函数
  4. 返回对象(构造函数返回对象时使用返回值,否则使用新对象)

用于深入理解 JavaScript 的对象实例化机制。