JS variable hoisting

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值