gpt4 book ai didi

javascript - 如何让ES6类的静态函数中的this指向函数本身

转载 作者:行者123 更新时间:2023-11-28 17:17:36 25 4
gpt4 key购买 nike

我想获取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技术上是非标准的,但它是compatible适用于所有主要浏览器,包括 IE。

关于javascript - 如何让ES6类的静态函数中的this指向函数本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53097642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com