Typescript: How to extend two classes?

前端 未结 9 1092
猫巷女王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: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);
    

提交回复
热议问题