从打字稿方法中获取方法名称

新手上路,请多包涵

我想从 Typescript 类的实例方法中获取当前方法的名称。

(伪代码,不起作用):

 class Foo {
    bar() {
        console.log(something); //what should something be?
    }
}

new Foo().bar();

我希望“某物”返回“酒吧”。我意识到 this 可以给我类,我可以以某种方式从中获取类及其属性,但我不知道如何获取“此功能”(即方法栏,而不是Foo 类)。

我已经看到其他几个与查找类名等相关的问题,但没有一个解决获取当前方法名的问题。

原文由 Anand 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 253
2 个回答

除了 arguments.callee.name 之外,没有直接的方法来获得它。

我建议另外两种方法:

使用装饰器注入方法名:

 function annotateName(target, name, desc) {
    var method = desc.value;
    desc.value = function () {
        var prevMethod = this.currentMethod;
        this.currentMethod = name;
        method.apply(this, arguments);
        this.currentMethod = prevMethod;
    }
}

class Foo {
    currentMethod: string;

    @annotateName
    bar() {
        alert(this.currentMethod);
        this.tux();
        alert(this.currentMethod);
    }

    @annotateName
    tux() {
        alert(this.currentMethod);
    }
}

new Foo().bar();

缺点是您必须注释要从中获取名称的所有函数。您可以改为只注释类,并在装饰器中迭代所有原型函数并应用相同的想法。


我的第二个选项不是标准化的,需要更加小心才能在浏览器中获得一致的结果。它依赖于创建一个错误对象并获取它的 堆栈 跟踪。

 class Foo {
    bar() {
        console.log(getMethodName());
    }
}

function getMethodName() {
    var err = new Error();
    return /at \w+\.(\w+)/.exec(err.stack.split('\n')[2])[1] // we want the 2nd method in the call stack

}

new Foo().bar();

原文由 Cristi Mihai 发布,翻译遵循 CC BY-SA 3.0 许可协议

不确定这是否有帮助,但是:

 class Foo {
    bar() {
        console.log(Object.getOwnPropertyNames(Foo.prototype)); // ["constructor", "bar"]
    }
}

new Foo().bar();

原文由 Slai 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题