一种TypeScript类独特的双重继承模式

一个独特的双重继承模式,允许开发者以两种不同的方式扩展基类:直接继承工厂函数方式。

实现方式

ts 复制代码
// 定义Module接口
interface IModule {
  exampleMethod(): number;
}

// 定义Module构造函数类型
interface ModuleConstructor {
  new (): IModule;
  (): typeof Module;
  prototype: IModule;
}

// 实现Module类
const Module = (function() {
  function Module(this: IModule) {
    if (!new.target) {
      return Module;
    }
  }

  // 添加原型方法
  Module.prototype.exampleMethod = function(this: IModule) {
    // @ts-ignore
    console.log('Method from Module',this.id);
  };

  return Module as unknown as ModuleConstructor;
})();

1. 类型系统设计

typescript 复制代码
interface IModule {
  exampleMethod(): number;
}

interface ModuleConstructor {
  new (): IModule;
  (): typeof Module;
  prototype: IModule;
}
  • IModule接口定义了模块的基本结构
  • ModuleConstructor接口实现了双重构造函数类型,支持两种实例化方式

2. 双重继承机制

Module类通过闭包和原型链操作实现了双重继承:

typescript 复制代码
const Module = (function() {
  function Module(this: IModule) {
    if (!new.target) {
      return Module;
    }
  }
  return Module as unknown as ModuleConstructor;
})();
  • 当使用new关键字时,创建普通实例
  • 当作为函数调用时,返回构造函数本身

重点: new.target 元属性允许你检测函数或构造函数是否是通过 new 运算符被调用的。在通过 new 运算符执行的函数或构造函数中,new.target 返回一个指向 new 调用的构造函数或函数的引用。在普通的函数调用中,new.target 的值是 undefined

使用方式

通过以上方式创建的Module即可以直接继承,也可以工厂方式继承。

1. 直接继承

typescript 复制代码
class MyModule extends Module {
  id = "my"
  test() {
    this.exampleMethod()
  }
}

2. 工厂函数方式

typescript 复制代码
class AnotherModule extends Module() {
  id = "another"
  test() {
    this.exampleMethod()
  }
}
相关推荐
kyriewen33 分钟前
看了微软几万人用AI编程的数据——效率涨24%的代价没人提
前端·ai编程·claude
2601_9637713735 分钟前
How to Scale Your WordPress Store Traffic in 2026
前端·php·plugin
亿元程序员44 分钟前
老板说我的3D箭头游戏用来做试玩太普通了,没人想玩,让我变点花样...
前端
李伟_Li慢慢1 小时前
01-threejs架构原理-课程简介
前端·three.js
_瑞3 小时前
深入理解 iOS 渲染原理
前端·ios
IT_陈寒3 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端
iCOD3R3 小时前
Skill - kill-ai-slop 解决“AI 味”样式
前端·css·ai编程
shuaijie05184 小时前
强制修改调用接口的api地址。
javascript·vue.js·ecmascript
JerrySir4 小时前
恶意 npm 包只活了 17 分钟:技术面试里,为什么“升级依赖”还不算止血?
javascript·安全
皮音4 小时前
Skill 在项目中的实践 —— 从 Agent 困境到 Skill 工程化
前端