1 let

基本用法

所声明的变量,只在let命令所在的代码块内有效。

{
    let b = 100;
    console.log(b); //100
}
    console.log(b); //Error

在for循环中适合使用let

不存在变量提升

let不像var那样会发生“变量提升”现象

{
    console.log(a); //undefined
    var a = 10;
    console.log(b); //b is not defined
    let b = 100;
}

暂时性死区

只要块级作用域内存在let命令,它所声明的变量就“绑定”(binding)这个区域,不再受外部的影响。

var a = 100;
{
    a = 10; //这里的a是let定义的a,而不是var定义的a,因为没有变量提升,所以报错
    let a;
}

不允许重复声明

let不允许在相同作用域内,重复声明同一个变量。

{
    let a;
    let a; //Identifier 'a' has already been declared
}

2 块级作用域

let实际上为JavaScript新增了块级作用域。

let a = 100;
{
    let a = 10;
    console.log(a); //10
}
console.log(a); //100

3 const命令

基本用法

const也用来声明常量,一旦声明不可改变

const a = 100;
a = 10; //Assignment to constant variable.

只声明不赋值也会报错

const a; //Missing initializer in const declaration

也存在块级作用域

{
    const a = 10;
    console.log(a); //10
}
console.log(a); //a is not defined

同样存在暂时性死区

{
    console.log(a); //a is not defined
    const a = 10;
}

也不可重复声明

{
    const a = 10;
    const a = 100; //Identifier 'a' has already been declared
}

指向复合类型变量地址不变,但对象本身可变

{
    const a = {};
    a.name = "Oliver";
    console.log(a.name); //Oliver
    a = {}; //Assignment to constant variable.
}

Object.freeze冻结对象

{
    const a = Object.freeze({});
    console.log(a); //Object {}
    a.name = "Oliver"; //不起作用
    console.log(a); //Object {}
}

4 全局对象的属性

let、const和class命令声明的全局变量不属于全局对象的属性

let a = 10;
console.log(a); //10
console.log(window.a); //undefined

JS菌
6.4k 声望2k 粉丝