0

我想在 ES6 类中获取静态函数名称,但这样做时我没有得到正确的结果。

class Point {
  static findPoint() {
    console.log(this.name) // <- I want to print "findPoint" but get "Point"
  }
}
Point.findPoint()

如何获取静态方法的名称?

4

2 回答 2

3

一种选择是创建一个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。

于 2018-11-01T08:41:19.810 回答
0

this.name指类名。用于this.findPoint.name获取静态函数名。语法必须是object.someMethod.name. 您必须说出您想要的方法名称。希望这会帮助你。

class Point {
  static findPoint() {
    console.log(this.findPoint.name)
  }
}
Point.findPoint()
于 2018-11-01T11:41:32.390 回答