【ES6專題】——var、let、const的區別和使用場景


  在ES6中,新出了let和const這兩個新的聲明變量的命令。與之前的var相比,let和const有幾個不同的特性。

 

var

  1. 可以重復聲明,且存在變量提升
  2. 沒有塊級作用域
        <!--可以重復聲明-->
        var a = "this is a";
        var a = "this is another a";    //重復聲明了a
        console.log(a);                 //輸出this is another a

        <!--存在變量提升-->
        console.log(b);     //變量提升,var b 被提升至所在作用域頂部,輸出undefined
        var b = "this is b";

        <!--無法限制修改-->
        var c = "this is c";
        c = "this is cc";
        c = "this is ccc";
        console.log(c);  //輸出this is ccc <!--沒有塊級作用域-->
        {
            var d = "this is d";
            console.log(d); //輸出this is d
        }
        console.log(d);     //輸出this is d

 

let

1.不能重復聲明,且不存在變量提升

2.塊級作用域

        <!--不能重復聲明-->
        let a = "this is a";
        let a = "this is another a";
        //這里會報錯:Uncaught SyntaxError: Identifier 'a' has already been declared

        <!--沒有變量提升-->
        console.log(b);
        let b = "this is b";
        //這里會報錯:Uncaught ReferenceError: b is not defined

        <!--塊級作用域-->
        {
            let c = "this is c";
            console.log(c);     //輸出this is c
        }
        console.log(c);
        //這里會報錯:Uncaught ReferenceError: c is not defined

 

const

const包含let的所有特性,區別是聲明的變量不可以修改(const保證變量指向的內存不可改動,而不是聲明的值不能改動

        <!--不能更改值-->
        const a = "this is a";
        a = "b";
        console.log(a);
        //這里報錯:Uncaught TypeError: Assignment to constant variable.

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM