<Exploring ES6> 读书笔记 - Variables and scoping

  1. var is function-scoped, let is block-scoped; //for (const x of ['a', 'b']) {} is ok

  2. let/const 有emporal dead zone (TDZ), 其实这和Java生命使用变量一直, 未声明前不可用. 但var声明但变量一旦进入这个变量声明但function, 即使还没到声明这行代码, 但是这个变量已经有了, 并且赋值为 undefined;

    let tmp = true;
    if (true) { // enter new scope, TDZ starts
    // Uninitialized binding for tmp is created
    console.log(tmp); // ReferenceError

     let tmp; // TDZ ends, `tmp` is initialized with `undefined`
     console.log(tmp); // undefined
    
     tmp = 123;
     console.log(tmp); // 123
    

    }
    console.log(tmp); // true
    例子2

    if (true) { // enter new scope, TDZ starts
    const func = function () {
    console.log(myVar); // OK!
    };

     // Here we are within the TDZ and
     // accessing `myVar` would cause a `ReferenceError`
    
     let myVar = 3; // TDZ ends
     func(); // called outside TDZ
    

    }

  3. always use const, let, 避免 var

标签: none

添加新评论