What is the point of using a named function expression?
This question already has an answer here:
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.
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, eg for recursion in an IEFE.
Also, named functions show up different during debugging, eg 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.
链接地址: http://www.djcxy.com/p/2840.html下一篇: 使用命名函数表达式有什么意义?