问题
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