Except for the traditionalObject oriented inheritanceThere is also a popular wayreusable component The way to create a class is toJoin another simple classThe code.

// Disposable Mixin
class Disposable {
  isDisposed: boolean;
  dispose() {
    this.isDisposed = true;

// Activatable Mixin
class Activatable {
  isActive: boolean;
  activate () {
    this.isActive = true;
  deactivate () {
    this.isActive = false;

//The smartobject class combines these two mixins. Instead of extensions, it uses implements,. Treat the class as an interface, using only the type of two mixins classes instead of the implementation. This means that we need to implement the interface in the class. But this is what we want to avoid when using mixins. So we can create placeholder properties for the property methods that will be mixins in.
class SmartObject implements Disposable, Activatable {
    setInterval(() => {
      console.log(`${this.isActive} : ${this.isDisposed}`);
    }, 500);

  interact () {

  isDisposed: boolean = false;
  dispose: () => void;

  isActive: boolean = false;
  activate: () => void;
  deactivate: () => void;

//Mix mixins into the defined classes to complete the whole implementation
applyMixins(SmartObject, [Disposable, Activatable]);

let smartObj = new SmartObject();
setTimeout(() => {
}, 1000);

//Create help functions to help us do the blending operation. It will traverse all the attributes on mixins, copy them to the target, and replace the previous occupied attributes with the real implementation code.
function applyMixins (deriveCtor: any, baseCtors: any[]) {
  baseCtors.forEach(baseCtor => {
    Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
      deriveCtor.prototype[name] = baseCtor.prototype[name];


This approach reminds me of the difference between interfaces and classes? (what’s the difference between the backend language and JS)

Recommended Today

Summary: NPM common commands and operations

The full name of NPM is (node package manager), which is a package management and distribution tool installed with nodejs. It is very convenient for JavaScript developersDownload, install, upload and manage installed packages。 First of all, the following variables will be used: < name > | < PKG > module name < version > version […]