Reputation: 562
I want get the static function name in ES6 class, and I did not get the correct result when I did this.
class Point {
static findPoint() {
console.log(this.name) // <- I want to print "findPoint" but get "Point"
}
}
Point.findPoint()
What can I do to get the name of the static method?
Upvotes: 0
Views: 48
Reputation: 87
this.name
refers class name. Use this.findPoint.name
to get static function name. Syntax must be object.someMethod.name
. You have to say which method name you want. Hope this will help you.
class Point {
static findPoint() {
console.log(this.findPoint.name)
}
}
Point.findPoint()
Upvotes: 0
Reputation: 370679
One option is to create an Error
and examine its stack - the top item in the stack will be the name of the current function:
class Point {
static findPoint() {
const e = new Error();
const name = e.stack.match(/Function\.(\S+)/)[1];
console.log(name);
}
}
Point.findPoint();
While error.stack
is technically non-standard, it's compatible with every major browser, including IE.
Upvotes: 3