命名匿名函数与匿名函数 [英] Named anonymous functions vs anonymous functions

查看:79
本文介绍了命名匿名函数与匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我对何时使用匿名函数感到困惑,例如:

So I am confused as to when I would use an anonymous function such as:

let foo = function () {
  //code
}

相对于命名的匿名函数,例如:

versus a named anonymous function such as:

let foo = function foo () {
  //code
}

除了对浏览器的支持(即IE)之外,两者之间是否还有其他区别?我什么时候应该在另一个上使用?

Besides browser support, namely IE, are there any differences between the two? When should I use one over the other?

推荐答案

在这种情况下,函数声明名称与为其分配的变量相同,则没有太大区别.

In this case, where the function declaration name is the same as the variable it is assigned to, it doesn't make much difference.

如果为定义和赋值使用了不同的名称,则在命名函数时,右侧的名称优先:

If you used a different name for the definition and assignment, the name on the right takes precedence in naming the function:

foo = function bar() {}
foo.name  // "bar"

在两种情况下,您都将函数分配给变量(函数表达式),但是在第一种情况下,您分配了未命名/匿名函数,而在第二种情况下,您分配了命名函数.当使用这种简单的表达式将匿名函数分配给变量时,JS引擎便能够正确命名该函数.

In both cases you assign your function to a variable (function expression), but in the first case you assign an unnamed/anonymous function, whereas in the second case you assign a named function. When assigning an anonymous function to a variable in such a simple expression, the JS engine is able to name the function properly.

请考虑以下情况,该分配对于引擎而言不是显而易见的:

Consider the following case where this assignment is non-obvious for the engine:

function p(fun) { return fun; }
foo = p(function() {})
foo.name  // empty string

TL; DR;使用命名函数,您通常可以获得更好的堆栈跟踪.

TL;DR; with named functions you often get better stack traces.

这篇关于命名匿名函数与匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆