Javascript Scope Of Function Declarations
Solution 1:
It belongs to the current scope, always. For example:
// global scope// foo is a global functionfunction foo() {
// bar is local to foofunction bar() {
}
}
Regarding your second question, this:
foo = function() {...}
is an anonymous function expression assigned to a global variable (unless you're running is strict mode, then foo
would be undefined). The difference between that and function foo() {}
is that the latter is a function declaration (versus a variable declaration, which is assigned an anonymous function expression).
You might be interested in this excellent article about function declarations and function expressions: Named function expressions demystified.
Solution 2:
Function declarations are always local to the current scope, like a variable declared with the var
keyword.
However, the difference is that if they are declared (instead of assigned to a variable) their definition is hoisted, so they will be usable everywhere in the scope even if the declaration comes in the end of the code. See also var functionName = function() {} vs function functionName() {}.
Solution 3:
Noteworthy distinction taking implicit globals into account:
var foo = function() {
// Variablesvar myVar1 = 42; // Local variable
myVar2 = 69; // Implicit global (no 'var')// Functional Expressionsvar myFn1 = function() { ... } // Local
myFn2 = function() { ... } // Implicit globalfunctionsayHi() {
// I am a function declaration. Always local.
}
}
Hopefully that clarifies a little. Implicit globals are defined if you forget a var
before your assignment. Its a dangerous hazard that applies to variable declarations and functional expressions.
Solution 4:
Your first example (var foo = function() {...}
) is called an anonymous function. It is dynamically declared at runtime, and doesn't follow the same rules as a normal function, but follows the rules of variables.
Post a Comment for "Javascript Scope Of Function Declarations"