命名匿名函数与匿名函数

命名匿名函数与匿名函数

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

问题描述

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

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;博士;使用命名函数,您通常可以获得更好的堆栈跟踪.

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

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

08-11 07:29