一种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()
  }
}
相关推荐
VisuperviReborn3 分钟前
React Native 与 iOS 原生通信:从理论到实践
前端·react native·前端框架
hashiqimiya9 分钟前
html的input的required
java·前端·html
soda_yo20 分钟前
JavaScripe中你所不知道的"变量提升"
javascript
Mapmost25 分钟前
WebGL三维模型标准(二)模型加载常见问题解决方案
前端
Mapmost26 分钟前
Web端三维模型标准(一):单位与比例、多边形优化
前端
www_stdio37 分钟前
JavaScript 执行机制详解:从 V8 引擎到执行上下文
前端·javascript
我命由我123451 小时前
HTML - 换行标签的 3 种写法(<br>、<br/>、<br />)
前端·javascript·css·html·css3·html5·js
暮冬十七1 小时前
[特殊字符] Vue3 项目最佳实践:组件命名、目录结构与类型规范指南
前端·前端架构·vue3项目搭建
F_Director1 小时前
简说Vue3 computed原理
前端·vue.js·面试
行走的陀螺仪1 小时前
Flutter 开发环境配置教程
android·前端·flutter·ios