问题
This question already has an answer here:
- var functionName = function() {} vs function functionName() {} 38 answers
- Why use named function expressions? 5 answers
I'm going through this blog about the difference between function declarations and function expressions.
It gives these two examples. They call the first an "anonymous function expression" and the second a "named function expression."
// anonymous function expression
var a = function(){
return 3;
}
// named function expression
var b = function bar(){
return 3;
}
I tested these two in Chrome's JS console and I see the following:
a()
=> 3
b()
=> 3
bar()
=> bar is not defined
My question is: In the second function expression declaration, what is the point of "bar"? In general, why does one ever use a named function expression?
回答1:
Some people prefer to do it like this because if errors occur, your functions have names. It's mostly a matter of preference and how often you have trouble with unnamed functions.
You don't normally see it used in a var
declaration, but instead when declaring callbacks:
callbackFunction(function success() { ... }, function fail() { ... })
That way you know which argument is which, they're labelled, and if one of them fails you get a precise indication of which one broke.
回答2:
var b = function bar(){ return 3; } bar() => bar is not defined
The identifier bar
is only available inside of the function. Try
var b = function bar() {
console.log(bar);
}
b();
why does one ever use a named function expression?
To allow referencing a function expression that was not assigned to a reachable or constant variable, e.g. for recursion in an IEFE.
Also, named functions show up different during debugging, e.g. in call stack (trace)s or breakpoint listings. Often you can use a (named) function declaration instead of a function expression, see also http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html.
来源:https://stackoverflow.com/questions/19303923/what-is-the-point-of-using-a-named-function-expression