问题
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