关于typescript:typescriptmixins

8次阅读

共计 2156 个字符,预计需要花费 6 分钟才能阅读完成。

在这篇文章中,将用简略清晰的术语向你介绍 TypeScript 中的 mixins 概念,即便你是老手。

在 TypeScript 中拓展类

就像许多面向对象的编程语言一样,TypeScript 也有类。类是创建对象的蓝图——它们基本上用于封装对象中的数据。TypeScript 类能够这样定义:

class Subscribe {Remind() {console.log("Remember to subscribe to my channel");
  }
}

该类蕴含一个名为 remind 的函数,该函数在 DOM 的控制台中记录字符串。如果你有一个新的命名为 Youtube 的类

class Youtube {Begin() {console.log("Hi, Welcome to my channel!");
  }
  Ending() {console.log("Thank you for watching my video!");
  }
}

如果你想有一个类来扩大咱们曾经定义的两个类,以便在这个新类中拜访它们,TypeScript 不容许这样做,所以它被标记为谬误。你能够这样试试:

export class Recording extends Youtube, Subscribe{}

如果你尝试过这样做,你会看到当你把鼠标悬停在 IDE 上时,会通知你 TypeScript 类只能扩大一个类的含糊行。当您第一次遇到这个问题时,您可能会想起 interfaces。

interfaces

在 TypeScript 中,类只能继承一个类,但接口能够继承多个类。应用 TypeScript 接口来解决咱们的问题:

export class Recording {}
export interface Recording extends Youtube, Subscribe {}
const recording = new Recording();
recording.Remind();
recording.Ending();

咱们创立一个接口,而后尝试查看是否能够拜访曾经定义的两个类中的函数。如果你在终端上运行 build:

tsc filename.ts
node filename.js

您将在构建的终端中看到一个谬误,阐明揭示和完结不是函数。这是因为 TypeScript 接口尽管能够扩大类,但却没有类的实现。这让咱们回到了最后的问题,即在 TypeScript 的一个新类中不能拜访多个类。

解决方案:Mixins

Mixins 是一种在面向对象编程范式中实现重用组件的办法。对于咱们后面的问题,能够是用一个 mixins 的辅助函数来解决,也就是在 TypeScript 的一个新类中扩大两个类。所以如果你是一个前端开发人员并应用 SASS,你可能对 mixins 很相熟。这是雷同的概念,但用于扩大类。这个 helper 函数能够在 TypeScript 的官网文档中找到。

function applyMixins(derivedCtor: any, baseCtors: any[]) {baseCtors.forEach((baseCtor) => {Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
      Object.defineProperty(
        derivedCtor.prototype,
        name,
        Object.getOwnPropertyDescriptor(baseCtor.prototype, name)
      );
    });
  });
}

当初你能够应用 ApplyMixins 函数来构建你的新类,像上面这样:

class Youtube {Begin(){console.log('Hi, Welcome to my channel!');
 }
 Ending(){console.log('Thank you for watching my video!');
 }
}
class Subscribe {Remind(){console.log('Remember to subscribe to my channel');
 }
}
// export class Recording extends Youtube, Subscribe{}
function applyMixins(derivedCtor: any, baseCtors: any[]) {
 baseCtors.forEach(baseCtor => {Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
   });
 });
}
export class Recording {}
export interface Recording extends Youtube, Subscribe{}
applyMixins(Recording,[Youtube, Subscribe]);
const recording = new Recording
recording.Remind();
recording.Ending();

总结

本文简略介绍了 TypeScript 的 Mixins 概念,以及如何应用它实现多类继承。

正文完
 0