typescript—mixins

Time:2020-2-15

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 {
  constructor(){
    setInterval(() => {
      console.log(`${this.isActive} : ${this.isDisposed}`);
    }, 500);
  }

  interact () {
    this.activate();
  }

  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(() => {
  smartObj.interact()
}, 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];
    });
  });
}

TODO:

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