function() { return msg; }
is just a value for funcDef
, like 5, true, and so on, and funcDef
is declared within the global scope (therefore visible everywhere).
Functions get access to the execution scope inside which they were created (and to the outer scopes as well). If you would have called a()
one more time the value for funcDef
would have been a different function with access to a different execution scope (since it was created inside another call of a
).
var funcDef;
function a(msg) {
funcDef = function() {
return msg;
}
}
a("foo");
a("bar");
console.log(funcDef()); // bar
Functions are visible within the scope in which they were created.
var funcDef;
function a() {
function f() { console.log(1); }
funcDef = f;
}
a();
funcDef(); // works
f(); // fails, not visible
by the way, rule of thumb:
- if the first token of a statement is the keyword function it's a function declaration (therefore it is hoisted to the top); if not it is a function expresion and it behaves like a normal variable declaration.
/* function declaration */
f(); // works
function f() { console.log(1); }
/* function expression */
g(); // fails
var g = function () { console.log(2); };
/* function expression */
namedFunc(); // fails
var h = function namedFunc() { console.log(1); };