Typescript: How to extend two classes?

前端 未结 9 1060
猫巷女王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:28

    In design patterns there is a principle called "favouring composition over inheritance". It says instead of inheriting Class B from Class A ,put an instance of class A inside class B as a property and then you can use functionalities of class A inside class B. You can see some examples of that here and here.

    0 讨论(0)
  • 2020-11-29 23:29

    A very hacky solution would be to loop through the class you want to inherit from adding the functions one by one to the new parent class

    class ChildA {
        public static x = 5
    }
    
    class ChildB {
        public static y = 6
    }
    
    class Parent {}
    
    for (const property in ChildA) {
        Parent[property] = ChildA[property]
    }
    for (const property in ChildB) {
        Parent[property] = ChildB[property]
    }
    
    
    Parent.x
    // 5
    Parent.y
    // 6
    

    All properties of ChildA and ChildB can now be accessed from the Parent class, however they will not be recognised meaning that you will receive warnings such as Property 'x' does not exist on 'typeof Parent'

    0 讨论(0)
  • 2020-11-29 23:33

    There are so many good answers here already, but i just want to show with an example that you can add additional functionality to the class being extended;

    function applyMixins(derivedCtor: any, baseCtors: any[]) {
        baseCtors.forEach(baseCtor => {
            Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
                if (name !== 'constructor') {
                    derivedCtor.prototype[name] = baseCtor.prototype[name];
                }
            });
        });
    }
    
    class Class1 {
        doWork() {
            console.log('Working');
        }
    }
    
    class Class2 {
        sleep() {
            console.log('Sleeping');
        }
    }
    
    class FatClass implements Class1, Class2 {
        doWork: () => void = () => { };
        sleep: () => void = () => { };
    
    
        x: number = 23;
        private _z: number = 80;
    
        get z(): number {
            return this._z;
        }
    
        set z(newZ) {
            this._z = newZ;
        }
    
        saySomething(y: string) {
            console.log(`Just saying ${y}...`);
        }
    }
    applyMixins(FatClass, [Class1, Class2]);
    
    
    let fatClass = new FatClass();
    
    fatClass.doWork();
    fatClass.saySomething("nothing");
    console.log(fatClass.x);
    
    0 讨论(0)
提交回复
热议问题