In Javascript, what is the motivation or advantage of using var foo = function foo(i) { … }?

荒凉一梦 提交于 2019-12-24 05:18:31

问题


I see that in the answer of

In Javascript, why write "var QueryStringToHash = function QueryStringToHash (query) { ... }"?

which is doing something like

var foo = function foo(param) {
  ...
}

in that particular case, why do that instead of just using

function foo(param) {
  ...
}

? What is the advantage or motivation of doing that?


回答1:


In shortly, if you take the following code, the first example creates a function, named foo, the second example creates an anonymous function and assign it to bar variable. Besides style, the basic difference is that foo can be called, in code, before it's definition (since it's the name of the function); otherwise, bar is an undefined variable before it receives the assignment, thus cannot be used before.

var foo_result = foo(123); // ok
function foo(param) { /* ... */ }

var bar_result = bar(123); // error: undefined is not a function
var bar = function(param) { /* ... */ }
var bar_result = bar(123); // ok

I'd recommend you to read the suggestion of @Pekka.



来源:https://stackoverflow.com/questions/3401290/in-javascript-what-is-the-motivation-or-advantage-of-using-var-foo-function-f

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