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

阿南德

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

(伪代码,不起作用):

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

new Foo().bar();

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

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

克里斯蒂·米海(Cristi Mihai)

除了之外,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();

缺点是您必须注释要从中获取名称的所有功能。相反,您可以仅对类进行注释,并在装饰器中迭代所有原型函数并应用相同的思想。


我的第二个选项不是标准化的,需要更多注意才能在浏览器之间获得一致的结果。它依赖于创建一个Error对象并获取它的堆栈跟踪。

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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章