How to get the function name from within that function?

前端 未结 20 1132
抹茶落季
抹茶落季 2020-11-22 16:06

How can I access a function name from inside that function?

// parasitic inheritance
var ns.parent.child = function() {
  var parent = new ns.parent();
  p         


        
20条回答
  •  执念已碎
    2020-11-22 16:41

    In ES6, you can just use myFunction.name.

    Note: Beware that some JS minifiers might throw away function names, to compress better; you may need to tweak their settings to avoid that.

    In ES5, the best thing to do is:

    function functionName(fun) {
      var ret = fun.toString();
      ret = ret.substr('function '.length);
      ret = ret.substr(0, ret.indexOf('('));
      return ret;
    }
    

    Using Function.caller is non-standard. Function.caller and arguments.callee are both forbidden in strict mode.

    Edit: nus's regex based answer below achieves the same thing, but has better performance!

提交回复
热议问题