Mixins

  1. // Disposable Mixin
  2. class Disposable {
  3. isDisposed: boolean;
  4. dispose() {
  5. this.isDisposed = true;
  6. }
  7. }
  8. // Activatable Mixin
  9. class Activatable {
  10. isActive: boolean;
  11. activate() {
  12. this.isActive = true;
  13. }
  14. deactivate() {
  15. this.isActive = false;
  16. }
  17. }
  18. class SmartObject implements Disposable, Activatable {
  19. constructor() {
  20. setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500);
  21. }
  22. interact() {
  23. this.activate();
  24. }
  25. // Disposable
  26. isDisposed: boolean = false;
  27. dispose: () => void;
  28. // Activatable
  29. isActive: boolean = false;
  30. activate: () => void;
  31. deactivate: () => void;
  32. }
  33. applyMixins(SmartObject, [Disposable, Activatable]);
  34. let smartObj = new SmartObject();
  35. setTimeout(() => smartObj.interact(), 1000);
  36. function applyMixins(derivedCtor: any, baseCtors: any[]) {
  37. baseCtors.forEach(baseCtor => {
  38. Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
  39. derivedCtor.prototype[name] = baseCtor.prototype[name];
  40. });
  41. });
  42. }