Get anonymous function name

前端 未结 4 1041
深忆病人
深忆病人 2020-12-06 21:00

How to get the the variable name from within a function in this example:

// it should return A
var A = function(){ console.log(this.name); } 
4条回答
  •  醉话见心
    2020-12-06 21:46

    No, there is nothing like that in Javascript. That function is anonymous, so it has no name, and what you want is ambiguous because the function could just as easily have any number of variables referencing it like:

    var a, b, c, d;
    a = b = function(){ console.log(this.name); };
    c = b;
    d = c;
    a = b = 5;
    // a and b no longer refer to the function, but c and d both do
    

    What is it you are actually trying to accomplish? I'm sure there is another way to achieve it.

提交回复
热议问题