Reputation: 365
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.
Upvotes: 17
Views: 13241
Reputation: 41
Previous answers will fail in certain cases
class cl_s2{
constructor(){
}
static a_static_method(){
var classname = this.toString().split ('(' || /s+/)[0].split (' ' || /s+/)[1];
console.log(classname);
}
static get is() {
return this.toString().replace(new
RegExp('^class(?: |\n|\r)+([^\s\n\r{]+)[\s\n\r{](?:\s|\n|\r|.)+', 'i'), '$1').trim();
}
static get className() {
let classNameRegEx = /(?:\S+\s+){1}([a-zA-Z_$][0-9a-zA-Z_$]*)/;
return classNameRegEx.exec( this.toString() )[1];
}
}
//Will fail in chrome because toString will return " class cl_s2{ ...", so there will be no "("
cl_s2.a_static_method();
//Will fail in browser which will display "function cl_s2(){" instead
// and in classes with underscore in name
console.log(cl_s2.is);
//this will work as long as you do not use unicode chars in classnames
console.log(cl_s2.className);
Upvotes: 4
Reputation: 1205
Improved method.
How to get class name in a static method
Useful for polymer 2.0 elements
The following code :
class G {
static get is() {
return this.toString().replace(new
RegExp('^class(?: |\n|\r)+([^\s\n\r{]+)[\s\n\r{](?:\s|\n|\r|.)+', 'i'), '$1').trim();
}
};
G.is
Gives you :
"G"
Upvotes: 0
Reputation: 1773
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
Upvotes: 7