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

时间:2021-11-16 03:39:25

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

}

2 个解决方案

#1


16  

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

#2


19  

This will work:

这将有效:

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

#1


16  

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

#2


19  

This will work:

这将有效:

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