Named anonymous functions vs anonymous functions

对着背影说爱祢 提交于 2021-02-04 19:17:25

问题


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
}

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


回答1:


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"

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; with named functions you often get better stack traces.



来源:https://stackoverflow.com/questions/48515483/named-anonymous-functions-vs-anonymous-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!