1. // 混入对象1
    2. class Bird {
    3. canFly: boolean;
    4. fly() {
    5. this.canFly = true;
    6. console.log('I can fly')
    7. }
    8. }
    9. // 混入对象2
    10. class Fish {
    11. canSwim: boolean;
    12. swim() {
    13. this.canSwim = true;
    14. console.log('I can swim')
    15. }
    16. }
    17. // 新对象
    18. class FlyFish implements Bird, Fish {
    19. constructor() {}
    20. canFly:boolean= false;
    21. canSwim:boolean= false;
    22. fly: () => void;
    23. swim: () => void;
    24. }
    25. function doMixins(derivedCtor: any, baseCtors: any[]) {
    26. baseCtors.forEach(baseCtor => {
    27. Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
    28. derivedCtor.prototype[name] = baseCtor.prototype[name];
    29. });
    30. });
    31. }
    32. doMixins(FlyFish, [Bird, Fish]);
    33. let flyFish = new FlyFish();
    34. console.log(flyFish.canFly);
    35. flyFish.swim();