我想在 ES6 类中获取静态函数名称,但这样做时我没有得到正确的结果。
class Point {
static findPoint() {
console.log(this.name) // <- I want to print "findPoint" but get "Point"
}
}
Point.findPoint()
如何获取静态方法的名称?
我想在 ES6 类中获取静态函数名称,但这样做时我没有得到正确的结果。
class Point {
static findPoint() {
console.log(this.name) // <- I want to print "findPoint" but get "Point"
}
}
Point.findPoint()
如何获取静态方法的名称?
一种选择是创建一个Error
并检查它的堆栈 - 堆栈中的顶部项目将是当前函数的名称:
class Point {
static findPoint() {
const e = new Error();
const name = e.stack.match(/Function\.(\S+)/)[1];
console.log(name);
}
}
Point.findPoint();
虽然error.stack
在技术上是非标准的,但它与所有主流浏览器兼容,包括 IE。
this.name
指类名。用于this.findPoint.name
获取静态函数名。语法必须是object.someMethod.name
. 您必须说出您想要的方法名称。希望这会帮助你。
class Point {
static findPoint() {
console.log(this.findPoint.name)
}
}
Point.findPoint()