简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM