Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve class name from within static method in typescript

I am trying to retrieve the class name from within a static method. It works from an ordinary method but not from within a static method

 class MyNode{
    constructor(){
        var classname=this.constructor.toString().split ('(' || /s+/)[0].split (' ' || /s+/)[1];
        console.log(classname);
    }
    static a_static_method(){
        var classname=this.constructor.toString().split ('(' || /s+/)[0].split (' ' || /s+/)[1];
        console.log(classname);
    }
}
var obj=new MyNode(); // THIS WORKS, prints "MyNode" 
MyNode.a_static_method(); // THIS DOESN'T, prints "Function"

I forgot to tell: it should work for the derived classes of MyNode.

like image 580
centeeth Avatar asked Apr 05 '16 12:04

centeeth


2 Answers

Now you can just use this.name

like image 180
aperpen Avatar answered Sep 28 '22 11:09

aperpen


Please check following solution:

class MyNode{
    constructor(){
        var classname=this.constructor.toString().split ('(' || /s+/)[0].split (' ' || /s+/)[1];
        console.log(classname);
    }
    static a_static_method(){
        var classname = this.toString().split ('(' || /s+/)[0].split (' ' || /s+/)[1];
        console.log(classname);
    }
}

In derived class you will get the name of that class, not MyNode

like image 22
lukbl Avatar answered Sep 28 '22 10:09

lukbl