How can I get the name of function inside a JavaScript function?

后端 未结 3 975
暖寄归人
暖寄归人 2020-12-13 09:12

How is it possible to learn the name of function I am in?

The below code alerts \'Object\'. But I need to know how to alert \"Outer.\"

function Oute         


        
相关标签:
3条回答
  • 2020-12-13 10:01

    I think that you can do that :

    var name = arguments.callee.toString();
    

    For more information on this, take a look at this article.

    function callTaker(a,b,c,d,e){
      // arguments properties
      console.log(arguments);
      console.log(arguments.length);
      console.log(arguments.callee);
      console.log(arguments[1]);
      // Function properties
     console.log(callTaker.length);
      console.log(callTaker.caller);
      console.log(arguments.callee.caller);
      console.log(arguments.callee.caller.caller);
      console.log(callTaker.name);
      console.log(callTaker.constructor);
    }
    
    function callMaker(){
      callTaker("foo","bar",this,document);
    }
    
    function init(){
      callMaker();
    }
    
    0 讨论(0)
  • 2020-12-13 10:08

    As of ES6, you can use Function.prototype.name. This has the added benefit of working with arrow functions, since they do not have their own arguments object.

    function logFuncName() {
      console.log(logFuncName.name);
    }
    
    const logFuncName2 = () => {
      console.log(logFuncName2.name);
    };
    
    0 讨论(0)
  • 2020-12-13 10:10

    This will work:

    function test() {
      var z = arguments.callee.name;
      console.log(z);
    }
    
    0 讨论(0)
提交回复
热议问题