Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

I have 3 classes:

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

class B extends A {

    constructor(){
        super();
        var baseDoStuff = super.DoStuff;
        this.DoStuff = function(){
            return baseDoStuff() + " and Called from B";
        }
    }
}

class C extends B { 
    constructor(){
        super();
        var baseDoStufffff = super.DoStuff;
        this.DoStuff = function(){
            return baseDoStufffff() + " and Called from C";
        }
    }
}

I expected class C's DoStuff() to call B's DoStuff() (which in turn would call A's).

However calling DoStuff() on C only returns "Called from A and Called from C". What am I doing wrong here? Shouldn't this call B's method too?

A working example of this can be found here:

Example

like image 813
Statue26 Avatar asked May 30 '13 14:05

Statue26


1 Answers

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

like image 173
basarat Avatar answered Sep 22 '22 03:09

basarat