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.
Now you can just use this.name
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With