一种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()
  }
}
相关推荐
xurileidian4 小时前
第 24 篇 · 边玩边学Python · while 与死循环怎么退
服务器·前端·python
Amumu121385 小时前
TypeScript学习: 基础知识(二)
开发语言·typescript·ecmascript
Highcharts.js5 小时前
Highcharts软件绘制图表:用数据构建可视化图形
前端·学习·信息可视化·数据分析·js·开发实战·highcharts
Amumu121386 小时前
TypeScript学习: 进阶知识
开发语言·学习·typescript
Hilaku7 小时前
2027 制药行业 ERP 系统架构选型笔记:从 GMP 合规追溯到动态 MCP 接入
前端·javascript·程序员
掘金安东尼8 小时前
人工智能AI
前端
kyriewen8 小时前
AI 面试官筛前端简历,先出局的不是写代码慢的
前端·面试·程序员
时间的情敌9 小时前
Three.js 后处理辉光 Bloom、告警发光效果、管线流光、着色器流动管线(ShaderMaterial)
开发语言·javascript·three.js·着色器
BigTopOne9 小时前
10 引用与借用:& 和 &mut
前端
粥里有勺糖9 小时前
视野修炼-技术周刊第139期 | AI 不会让时间变多
前端·github·ai编程