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

pen*_*ake 26 javascript function typeof

怎么可能学习我所在的职能名称?

以下代码警告'对象'.但我需要知道如何警告"外面".

function Outer(){

    alert(typeof this);

}
Run Code Online (Sandbox Code Playgroud)

yan*_*nis 29

这将有效:

function test() {
  var z = arguments.callee.name;
  console.log(z);
}
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案,而不是选择的答案。 (2认同)

mar*_*cgg 17

我认为你可以这样做:

var name = arguments.callee.toString();
Run Code Online (Sandbox Code Playgroud)

有关这方面的更多信息,请查看本文.

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 我不确定arguments.callee是否已被弃用.Function.arguments和Function.arguments.callee是函数参数的callee属性,但不是函数参数的callee属性.从MDC: - JavaScript 1.4:不推荐的被调用者作为Function.arguments的属性,将其保留为函数的本地参数变量的属性. (4认同)
  • 不幸的是`arguments.callee`已被弃用,但由于ECMA尚未定义任何替代品,因此这是可行的方法. (3认同)

jab*_*tta 5

从ES6开始,您可以使用Function.prototype.name。这具有使用箭头功能的额外好处,因为它们没有自己的参数对象。

function logFuncName() {
  console.log(logFuncName.name);
}

const logFuncName2 = () => {
  console.log(logFuncName2.name);
};
Run Code Online (Sandbox Code Playgroud)

  • 不想使用函数本身的名称该怎么办?诸如“ this.name”之类的东西,其中“ this”表示“ this function”而不是“ this class”? (6认同)