ES6 学习系列---《let》

  • 暂时性死区 temporal dead zone TDZ

ES6中规定,区块中存在const/let命令,则该区块对这些命令声明的变量从一开始就形成封闭作用域,只要在声明之前使用这些变量就会报错。

var tmp = 123;
if (true) {
    //TDZ开始
    tmp = 234; //Uncaught ReferenceError: tmp is not defined
    let tmp; //TDZ结束
}
var tmp = 123;
if (true) {
    tmp = 234;
    const tmp; //Uncaught SyntaxError: Missing initializer in const declaration
}
var tmp = 123;
if (true) {
    tmp = 234; // Uncaught ReferenceError: tmp is not defined
    const tmp=123;
}

TDZ本质:进入作用域时,所需变量就已经存在,但是不能获取。只有等到声明变量的那一行出现,才能获取/使用该变量。

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

function fun () {
    var a = 20;
    let a = 10;
    console.log(a);
}

fun();// Uncaught SyntaxError: Identifier 'a' has already been declared

function fun (args) {
    let args;
    console.log(args);
}

fun(args); // Uncaught SyntaxError: Identifier 'a' has already been declared
let args;
function fun (args) {
    {
        let args;
        console.log(args);
    }
}

fun(args);

//正确运行:undefined
发布了91 篇原创文章 · 获赞 18 · 访问量 3150

猜你喜欢

转载自blog.csdn.net/A_bad_horse/article/details/105025824
今日推荐