从typescript方法中获取方法名称

Ana*_*and 6 javascript typescript

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

(伪代码,不起作用):

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

new Foo().bar();
Run Code Online (Sandbox Code Playgroud)

我希望'某事'能够回归'酒吧'.我意识到this可以给我这个类,我可以以某种方式从它获得类及其属性,但我不知道如何获得'这个函数'(即方法栏,而不是类Foo).

我已经看到了几个与查找类名等有关的问题,但没有找到解决当前方法名称的问题.

Cri*_*hai 12

除此之外,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();
Run Code Online (Sandbox Code Playgroud)

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


我的第二个选项不是标准化的,需要更多关注以在浏览器之间获得一致的结果 它依赖于创建一个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();
Run Code Online (Sandbox Code Playgroud)

  • 请解释一下您从“annotateName”函数中获取“this”和“arguments”的位置。 (2认同)