Extending base class methods with multiple levels of inheritance (typescript)

前端 未结 2 1283
长情又很酷
长情又很酷 2021-02-19 06:48

I have 3 classes:

class A{
    DoStuff(){
        return \"Called from A\";
    }
}

class B extends A {

    constructor(){
        super();
        var baseDo         


        
2条回答
  •  余生分开走
    2021-02-19 07:00

    Whenever you need to use super Use class methods instead of class members:

    class A{
        DoStuff(){
            return "Called from A";
        }
    }
    
    class B extends A {
    
        constructor(){
            super();      
    
        }   
        DoStuff (){
            return super.DoStuff() + " and Called from B";
        }
    }
    
    class C extends B { 
        constructor(){
            super();                
        }
    
        DoStuff(){
                return super.DoStuff() + " and Called from C";
        }
    }
    
    var c = new C();
    console.log(c.DoStuff());
    

    Try it (prints Called from A and Called from B and Called from C)

    This is because super translates to .prototype i.e. super.DoStuff() becomes _super.prototype.DoStuff() and the only things available on .prototype are class methods.

    More: http://basarat.github.io/TypeScriptDeepDive/#/super

提交回复
热议问题