JS Hoisting
在function内
Example 1 - 没有用 var 来declare variable. Hoisting will happen.
Example 2 - 有用 var 来declare variable
Example 1
t2.js
- 注意: 以下的 a 变量 没有 用 var 来declare。
function foo(x){
if (x > 5){
a = 'positive'
}else{
a = 'negative'
}
console.log("inside foo=",a);
}
foo(100)
console.log("outside foo=",a)
-output
inakamono@ninja MINGW64 ~/wk/coding/es6-the-right-parts/ex0
$ node t2.js
inside foo= positive
outside foo= positive
(base)
t2.js 的 a 变量会被 hoisted 提升至 global context 如下
var a// 《------a 被 hoisted 提升至 global context
function foo(x){
if (x > 5){
a = 'positive'
}else{
a = 'negative'
}
console.log("inside foo=",a);
}
foo(100)
console.log("outside foo=",a) ;
Example 2
function foo(x){
if (x > 5){
var a = 'positive'
}else{
var a = 'negative'
}
console.log("inside foo=",a);
}
foo(100)
console.log("outside foo=",a) ;
- output
解释:在 foo function 内declare 的var a 的scope 没有被hoisted 至 global context. var a 的scope 只有被限制在 foo function 内。 所以 run 了foo(100) 之后, a 就不能被 called 了。
inakamono@ninja MINGW64 ~/wk/coding/es6-the-right-parts/ex0
$ node t2.js
inside foo= positive
C:\Users\inakamono\wk\coding\es6-the-right-parts\ex0\t2.js:10
console.log("outside foo=",a) ;
^
ReferenceError: a is not defined
at Object.<anonymous> (C:\Users\inakamono\wk\coding\es6-the-right-parts\ex0\t2.js:10:28)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11