ES6--let关键字

1.let关键字声明的变量,只在块中有效

if(true){
    var a = 5;
    let b = 5;
}

console.log(a);

console.log(b);
 
================分割线================
运行结果:

 

2.let关键字可以防止循环变量的泄露,同时能够提供闭包

for(let i = 0; i < 5; i++){
    console.log(i);
}

console.log('here', i);

 

================分割线================
运行结果:

 

 如果去掉最后一行,即:

for(let i = 0; i < 5; i++){
    console.log(i);
}
 
================分割线================
运行结果:
 
3.let不会进行变量提升
console.log(a);
let a = 5;

 4.暂时性死区:

let不进行变量提升,他会绑定到一个块作用域上;

变量提升:var 在预编译时将变量产生,只是数值没有初始化,所以可以访问;

绑定:let 在预编译时变量产生,但是在let声明之前,不允许使用,从块作用域的头部到let声明之间的范围(暂时性死区 TDS)

let b = 5;
if(true){
    console.log(b);
 // TDS
    let b;
 //undefined
 b = 3;
 // 3
}
5.let 不允许在同一个作用域内重复定义
{
    let b = 5;
    let b = 3;
    console.log(b);
}

 6.let声明的变量:内层可以访问外层的变量,外层不能访问内层的变量

let a = 5;

{

  console.log(a);

}

 

 

{

  let b = 4;

  console.log(b);

}

 

 

{

  let b = 4;

}

console.log(b);

 

 

// 7.块级作用域中的函数声明
//    ES5:不允许在块结构中声明函数的
//    ES6:1.允许在块结构中声明函数的
//        2.函数依然有预编译,函数名会提升到全局作用域或者函数作用域的头部
//        3.如果在块级作用域,会提升到块的头部
function f() {
    console.log('outside!');
}

(function () {
    if(false) {
        function f() {
            console.log('inside!');
        }
    }
    f();
})();
===========ES5中运行结果===========

 

 

============ES6中运行结果===========

 

 

 

posted @ 2021-01-11 22:27  #Friday  阅读(132)  评论(0)    收藏  举报