How to get the function name from within that function?

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

    You could use Function.name:

    In most implementations of JavaScript, once you have your constructor's reference in scope, you can get its string name from its name property (e.g. Function.name, or Object.constructor.name

    You could use Function.callee:

    The native arguments.caller method has been deprecated, but most browsers support Function.caller, which will return the actual invoking object (its body of code): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fcaller

    You could create a source map:

    If what you need is the literal function signature (the "name" of it) and not the object itself, you might have to resort to something a little more customized, like creating an array reference of the API string values you'll need to access frequently. You can map them together using Object.keys() and your array of strings, or look into Mozilla's source maps library on GitHub, for bigger projects: https://github.com/mozilla/source-map

提交回复
热议问题