How to get the function name from within that function?

前端 未结 20 877
抹茶落季
抹茶落季 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:24

    This might work for you:

    function foo() { bar(); }
    
    function bar() { console.log(bar.caller.name); }
    

    running foo() will output "foo" or undefined if you call from an anonymous function.

    It works with constructors too, in which case it would output the name of the calling constructor (eg "Foo").

    More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller

    They claim it's non-standard, but also that it's supported by all major browsers: Firefox, Safari, Chrome, Opera and IE.

提交回复
热议问题