在 JavaScript 中获取函数名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3178892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:34:02  来源:igfitidea点击:

Get function name in JavaScript

javascript

提问by kalan

Does anyone know if there is a way to get JavaScript function name. For example I got a function like

有谁知道是否有办法获取 JavaScript 函数名称。例如我得到了一个像

function test1(){
alert(1);
}

I have it in my head section. Then I create an object obj1 and put my function there

我有它在我的头部部分。然后我创建一个对象 obj1 并将我的函数放在那里

obj1.func = test1;

When I call a method in obj1 object, do I have any way to get my function name (test1) inside of this method, except parsing the source (this.func.toString()) of the function.

当我调用 obj1 对象中的方法时,除了解析this.func.toString()函数的源 ( )之外,我有没有办法在该方法中获取我的函数名称 (test1) 。

回答by Kamil Szot

function test() {  alert(arguments.callee.name); } 
b = test; 
b();

outputs "test" (in Chrome, Firefox and probably Safari). However, arguments.callee.nameis only available from insidethe function.

输出“测试”(在 Chrome、Firefox 和可能的 Safari 中)。但是,arguments.callee.name只能从函数内部使用。

If you want to get name from outsideyou may parse it out of:

如果您想从外部获取名称,您可以将其解析为:

b.toString();

but I think name property of function object might be what you need:

但我认为函数对象的 name 属性可能是您需要的:

alert(b.name);

this however does not seem work for IE and Opera so you are left with parsing it out manually in those browsers.

然而,这似乎不适用于 IE 和 Opera,因此您只能在这些浏览器中手动解析它。

回答by Vlad A Ionescu

The best thing to do is:

最好的做法是:

function functionName(fun) {
  var ret = fun.toString();
  ret = ret.substr('function '.length);
  ret = ret.substr(0, ret.indexOf('('));
  return ret;
}

Note: Using Function.calleris non-standard and arguments.calleeis forbidden in strict mode.

注意:使用Function.caller是非标准的,arguments.callee在严格模式下是禁止的。

回答by Tim Down

Until ES2015, there was no standard way to get the name of a function. Most current browsers support a nameproperty on Functionobjects that was non-standard until ES2015, but no current version of IE does. The only option this leaves you if you need to support IE is trying to parse the name from the function's string representation, which is not a good idea. There's a (long) discussion here about it: http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/b85dfb2f2006c9f0

ES2015之前,没有标准的方法来获取函数的名称。当前大多数浏览器都支持ES2015 之前非标准的对象name属性Function,但当前版本的 IE 不支持。如果您需要支持 IE,唯一的选择是尝试从函数的字符串表示中解析名称,这不是一个好主意。这里有一个(长)讨论:http: //groups.google.com/group/comp.lang.javascript/browse_frm/thread/b85dfb2f2006c9f0

回答by kybernetikos

Here's what I use to put class names in error messages. It includes code to get the name of functions, which works in most browsers.

这是我用来将类名放在错误消息中的内容。它包含用于获取函数名称的代码,该代码适用于大多数浏览器。

Obviously, there is no standard way that always works, so you should always provide a name that can be used if no other name is found.

显然,没有始终有效的标准方法,因此您应该始终提供一个可以在找不到其他名称时使用的名称。

var nameFromToStringRegex = /^function\s?([^\s(]*)/;

/**
 * Gets the classname of an object or function if it can.  Otherwise returns the provided default.
 *
 * Getting the name of a function is not a standard feature, so while this will work in many
 * cases, it should not be relied upon except for informational messages (e.g. logging and Error
 * messages).
 *
 * @private
 */
function className(object, defaultName) {
    var result = "";
    if (typeof object === 'function') {
        result = object.name || object.toString().match(nameFromToStringRegex)[1];
    } else if (typeof object.constructor === 'function') {
        result = className(object.constructor, defaultName);
    }
    return result || defaultName;
}

回答by jdotjdot

One interesting way I'm experimenting with is a declaration like the following:

我正在试验的一种有趣方式是如下声明:

var test1 = function test1(){
    alert(1);
};

It's a little hacky, but what ends up happening is test1is a local variable that holds a [Function: test1]object.

这有点棘手,但最终发生的test1是一个保存[Function: test1]对象的局部变量。

Here's what happens when you use code based on it:

当您使用基于它的代码时,会发生以下情况:

test1(); //runs the function as expected
console.log(test1.name); //prints 'test1'

So if you do the following:

因此,如果您执行以下操作:

obj1.func = test1;

You'll then be able to reference obj1.func.nameand it'll return 'test1'.

然后,您将能够引用obj1.func.name,它会返回'test1'.

回答by imalvinz

This is probably the best way to do it:

这可能是最好的方法:

var myfunc = function () {};
var funcName = myfunc.constructor.name;

This can be done outside the execution of the function, and you can check within the context of the browser console.

这可以在函数执行之外完成,您可以在浏览器控制台的上下文中进行检查。

Happy coding!

快乐编码!

回答by yckart

You could convert your function into a string (fn + '')and split it later at whitespace and open bracket/\s|\(/.

您可以将您的函数转换为一个字符串(fn + ''),然后在空格和开括号处将其拆分/\s|\(/

var getFunctionName = function (fn) {
   return (fn + '').split(/\s|\(/)[1];
};