javascript - arguments.callee.toString() and arguments.callee.name does not return function name

后端 未结 8 2046
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 04:30

I\'m trying to get the name of the currently running function. From what I\'ve read, this should be possible using:

(arguments.callee.toString()).match(/func         


        
相关标签:
8条回答
  • Function.prototype.getName = function(fn) {
        if(Function.name || Function.prototype.name) return this.name;
        return this.toString().match(/^function\s+(\w+)\s*\(/)[1];
    };
    
    0 讨论(0)
  • 2021-01-05 05:11

    I think there's a much cleaner and elegant solution to all this. Assuming the function is a member of some higher-level object—and that's always going to be the case, even if the function's owner is "window" or some other global object, we can access the global object via the this keyword, we can access the function itself via arguments.callee and we can access all the parent's object (function) names via for (var o in this), so you should be able to get the desired information fairly easily as...

    returnMyName = function() {
      for (var o in this) {
        if (arguments.callee===this[o]) return o;
      }
    };
    

    That should be robust and avoid any weird IE browser behaviors accessing named functions, etc.

    0 讨论(0)
提交回复
热议问题