Typescript: How to extend two classes?

前端 未结 9 1111
猫巷女王i
猫巷女王i 2020-11-29 22:38

I want to save my time and to reuse common code across classes which extends PIXI classes (a 2d webGl renderer library).

Object Interfaces:

9条回答
  •  不知归路
    2020-11-29 23:19

    There is a little known feature in TypeScript that allows you to use Mixins to create re-usable small objects. You can compose these into larger objects using multiple inheritance (multiple inheritance is not allowed for classes, but it is allowed for mixins - which are like interfaces with an associated implenentation).

    More information on TypeScript Mixins

    I think you could use this technique to share common components between many classes in your game and to re-use many of these components from a single class in your game:

    Here is a quick Mixins demo... first, the flavours that you want to mix:

    class CanEat {
        public eat() {
            alert('Munch Munch.');
        }
    }
    
    class CanSleep {
        sleep() {
            alert('Zzzzzzz.');
        }
    }
    

    Then the magic method for Mixin creation (you only need this once somewhere in your program...)

    function applyMixins(derivedCtor: any, baseCtors: any[]) {
        baseCtors.forEach(baseCtor => {
            Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
                 if (name !== 'constructor') {
                    derivedCtor.prototype[name] = baseCtor.prototype[name];
                }
            });
        }); 
    }
    

    And then you can create classes with multiple inheritance from mixin flavours:

    class Being implements CanEat, CanSleep {
            eat: () => void;
            sleep: () => void;
    }
    applyMixins (Being, [CanEat, CanSleep]);
    

    Note that there is no actual implementation in this class - just enough to make it pass the requirements of the "interfaces". But when we use this class - it all works.

    var being = new Being();
    
    // Zzzzzzz...
    being.sleep();
    

提交回复
热议问题