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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • let 命令 块级作用域 const 命令 顶层对象的属性 global 对象 let 命令 基本用法 ES6 新...
    嘉奇呦_nice阅读 5,543评论 0 2
  • let 命令 块级作用域 const 命令 顶层对象的属性 global 对象 let 命令 基本用法 ES6 新...
    卞卞村长L阅读 3,775评论 0 0
  • let 和 const 命令 let 命令 块级作用域 const 命令 顶层对象的属性 gl...
    安小明阅读 4,562评论 0 0
  • 1 let ES6 新增了let命令,用来声明变量。它的用法类似于var,但是所声明的变量,只在let命令所在的...
    yujiawei007阅读 1,396评论 0 0
  • 1.let命令 基本用法 ES6 新增了let命令,用来声明变量。它的用法类似于var,但是所声明的变量,只在le...
    angelwgh阅读 2,271评论 0 0

友情链接更多精彩内容