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?
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.