JavaScript (6) Function: Hoisting, Nested Scopes and Strict Mode
1. Hoisting of variable:
Hoisting is JavaScript's default behaviour of moving declarations to the top.
a = 2; console.log(a); var a;
The program which is shown above is similar to:
var a; a = 2; console.log(a);
The declaration of "a" is moved to the top.
2. Hoisting of function:
Hoisting of function is slightly different.
foo();
function foo() {
console.log("Hello foo");
}
The function body is moved to the top like:
function foo() {
console.log("Hello foo");
}
foo();
If you have two functions to be hoisted, both are hoisted but the latest one would override the previous function:
foo(); // foo2
function foo() {
console.log("foo1");
}
function foo() {
console.log("foo2");
}
We can declare a variable and assign the function to the variable.
foo(); // Error
var foo = function() {
console.log("foo");
}
Only the declaration of the variable is moved to the top.
var foo;
foo(); // Error
foo = function() {
console.log("foo");
}
3. Nested Scopes:
When you declare a variable, it is available anywhere in that scope, as well as any lower/inner scopes.
var foo = function() {
var a = 10;
console.log(a);
var bar = function() {
// the scope of bar is inside the scope of foo
// variable a is available in the inner scope
console.log(a);
};
bar();
};
foo();
4. Strict Mode
If you create a variable in a function without using var identifier, that variable would be global which means you can access it anywhere.
var foo = function() {
// create a global variable
a = 10;
};
foo();
// use gloabal variable a
console.log(a);
var foo = function() {
// create a local variable
var a = 10;
};
foo();
// a is a local variable in foo
// which can't be accessed outside
console.log(a);
We can use strict mode in the function to prevent creating global variable. Strict mode also works in the inner scopes.
var foo = function() {
"use strict";
a = 10;
};
foo();
Reference
[1] Kyle Simpson, You Don't Know JS Series, O'Reilly Media (2014)
留言
張貼留言