What is the point of using a named function expression? [duplicate]

别等时光非礼了梦想. 提交于 2019-11-28 11:35:11

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, 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.

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