let和const命令

1. 塊級(jí)作用域 {}

{}語法在es6之前就已存在,但沒有作用域的特性,例如:

{
    var a = 123;

    console.log(a);  // 123
}
console.log(a); // 123

在ie7+也是可以正常運(yùn)行的(ie6我已放棄測(cè)試)

而在es6中,在{}中使用let和const申明的變量的作用域會(huì)被{}限制在其中,而var不會(huì)被限制

{
    let a = 123;
    const b = 11;
    var c = 33;

    console.log(a); // 123
    console.log(b); // 11
    console.log(c); // 33
}

console.log(a); // a is not defined
console.log(b); // b is not defined
console.log(c); // 33

2. 不存在變量提升現(xiàn)象

// var 的情況
console.log(foo); // 輸出undefined
var foo = 2;

// let 的情況
console.log(bar); // bar is not defined
let bar = 2;

// const 的情況
console.log(bar); // bar is not defined
let const = 2;

3. 塊級(jí)作用域的函數(shù)申明

ES5 規(guī)定,函數(shù)只能在頂層作用域和函數(shù)作用域之中聲明,不能在塊級(jí)作用域聲明, 例如

if (true) {
    function f() {
        console.log('hello')
    }
}

f();  // 輸出 hello

上面兩種函數(shù)聲明,根據(jù) ES5 的規(guī)定都是非法的。但是,瀏覽器沒有遵守這個(gè)規(guī)定,為了兼容以前的舊代碼,還是支持在塊級(jí)作用域之中聲明函數(shù),因此上面兩種情況實(shí)際都能運(yùn)行,不會(huì)報(bào)錯(cuò)。但如果在嚴(yán)謹(jǐn)模式下是會(huì)報(bào)錯(cuò)的;

'use strict'
if (true) {
    function f() {
        console.log('hello')
    }
}

f(); // 報(bào)錯(cuò) f is not  defined

在es5中的{}申明函數(shù),是會(huì)有申明提前的現(xiàn)象,例如:

if(false) {
    function a() {
        console.log('123')
    }
}

a(); // 輸出123 無視if條件

在es6中:

if(false) {
    function a() {
        console.log('123')
    }
}

a(); // a is not defined
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • let 命令 塊級(jí)作用域 const 命令 頂層對(duì)象的屬性 global 對(duì)象 let 命令 基本用法 ES6 新...
    嘉奇呦_nice閱讀 1,694評(píng)論 0 2
  • let 命令 塊級(jí)作用域 const 命令 頂層對(duì)象的屬性 global 對(duì)象 let 命令 基本用法 ES6 新...
    卞卞村長(zhǎng)L閱讀 680評(píng)論 0 0
  • let 和 const 命令 let 命令 塊級(jí)作用域 const 命令 頂層對(duì)象的屬性 gl...
    安小明閱讀 1,039評(píng)論 0 0
  • 1 let ES6 新增了let命令,用來聲明變量。它的用法類似于var,但是所聲明的變量,只在let命令所在的...
    yujiawei007閱讀 200評(píng)論 0 0
  • 1.let命令 基本用法 ES6 新增了let命令,用來聲明變量。它的用法類似于var,但是所聲明的變量,只在le...
    angelwgh閱讀 319評(píng)論 0 0

友情鏈接更多精彩內(nèi)容