Get method name from within a typescript method

前端 未结 5 1086
陌清茗
陌清茗 2021-01-04 07:33

I want to get the name of the current method from within an instance method of a class in Typescript.

(Pseudocode, doesn\'t work):

class Foo {
    ba         


        
5条回答
  •  粉色の甜心
    2021-01-04 07:46

    Just to answer the question with another interesting take, you could do (but shouldn't do) something like this:

    class Foo {
        constructor(private http: HttpClient) {
    
            const apiUrl = 'http://myapi.com/api/';
    
            {
                const functionName = 'getBar';
                this[functionName] = function () {
                    return http.get(apiUrl + functionName);
                }
            }
    
            {
                const functionName = 'postBar';
                this[functionName] = function () {
                    return http.get(apiUrl + functionName);
                }
            }
    
            {
                const functionName= 'putBar';
                this[functionName] = function () {
                    return http.get(apiUrl + functionName);
                }
            }
    
            {
                const functionName= 'deleteBar';
                this[functionName] = function () {
                    return http.get(apiUrl + functionName);
                }
            }
        }
    }
    

    It certainly is not an elegant solution, and I can't really imagine a good use case for doing something like this, as I'm pretty sure the compiler doesn't recognize new Foo(http).deleteBar(). Maybe someone can come up with an elegant solution with this idea, I'll leave that as an experiment for someone.

    But with this pattern (if you employ some kind of devops scaffolding or "strong copy-paste skills") you can always access your method's name via functionName

提交回复
热议问题