let和const命令

1. 块级作用域 {}

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

{
    var a = 123;

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

在ie7+也是可以正常运行的(ie6我已放弃测试)

而在es6中,在{}中使用let和const申明的变量的作用域会被{}限制在其中,而var不会被限制

{
    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. 不存在变量提升现象

// 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. 块级作用域的函数申明

ES5 规定,函数只能在顶层作用域和函数作用域之中声明,不能在块级作用域声明, 例如

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

f();  // 输出 hello

上面两种函数声明,根据 ES5 的规定都是非法的。但是,浏览器没有遵守这个规定,为了兼容以前的旧代码,还是支持在块级作用域之中声明函数,因此上面两种情况实际都能运行,不会报错。但如果在严谨模式下是会报错的;

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

f(); // 报错 f is not  defined

在es5中的{}申明函数,是会有申明提前的现象,例如:

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

a(); // 输出123 无视if条件

在es6中:

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

a(); // a is not defined

你可能感兴趣的:(let和const命令)