简体   繁体   English

如何在 JavaScript 函数中获取函数的名称?

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

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 Outer(){

    alert(typeof this);

}

This will work: 这将有效:

function test() {
  var z = arguments.callee.name;
  console.log(z);
}

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();
}

As of ES6, you can use Function.prototype.name . 从ES6开始,您可以使用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);
};

Took me a while to figure this out, so tried to make it very clear for rookies like me.我花了一段时间才弄明白这一点,所以试着让像我这样的新手说清楚。

Approach 1 - arguments.callee.name方法 1 - arguments.callee.name

This approach used to work, but now in ES6 Strict Mode it will fail.这种方法曾经有效,但现在在 ES6 严格模式下它会失败。 Don't use Approach 1.不要使用方法 1。

//approach 1 - don't use
let functionName = arguments.callee.name;
console.log(functionName);

Approach 2 - create a function and use caller.name方法 2 - 创建一个函数并使用 caller.name

This approach works in the latest version of Javascript and will not fail in Strict Mode. 这种方法适用于最新版本的 Javascript,在严格模式下不会失败。 Use Approach 2. There are 2 steps.使用方法 2。有 2 个步骤。

Step 1 - Create a function that uses caller.name to return the name of the function that called it.步骤 1 - 创建一个函数,该函数使用 caller.name 返回调用它的函数的名称。 Add this function to your code:将此函数添加到您的代码中:

function getFuncName() {
   return getFuncName.caller.name
}

Step 2 - Call your function when you need the name of the function your code is currently in.第 2 步 - 当您需要代码当前所在函数的名称时调用您的函数。

    function iWantThisName() { 
      console.log(getFuncName())
    }
    
    iWantThisName() 
    // Logs: "iWantThisName"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM