Consider two styles of javascript function declarations (out of four, I think):
function foo() {
// ...
}
versus
var foo = function() {
// ...
}
In many circumstances these will behave the same, and I think I grok the main difference as explained in e.g. these SO questions:
difference-between-var-foo-function-and-function-foo
usual-functions-vs-function-variables-in-javascript
which both have answers linking to this very helpful explanation:
javascript-function-declaration-ambiguity
But I would like to combine both styles in one statement; one short/minifiable local variable name (because I will need to refer to it quite often) and one descriptive name (I want to get something friendly out of .name
).
This is where I get confused. It is as if the act of immediately assigning the function to a variable leaves it undefined under its own name:
var f = function foo() {
// ...
};
console.log( f.name ); // "foo"
console.log( foo.name ); // !? error: foo is not defined ?!
So to get to the question: why does this not work? Or, more likely, what might I still be misunderstanding about these two declaration styles?
Note, that the following does not result in an error:
var f = foo;
function foo() {
// ...
}
console.log( f.name ); // "foo"
console.log( foo.name ); // "foo"
How, exactly, is this different?
PS: I think this is different from this SO question:
in-javascript-what-is-the-motivation-or-advantage-of-using-var-foo-function-f...
which is about a special case of my predicament, where the variable name and function name are the same, i.e.
var foo = function foo() {
// ...
};