hoisting-vs-tdz

hoisting-vs-tdz.md

In JavaScript, all binding declarations are instantiated when control flow enters the scope in which they appear. Legacy var and function declarations allow access to those bindings before the actual declaration, with a "value" of undefined. That legacy behavior is known as "hoisting". let and const binding declarations are also instantiated when control flow enters the scope in which they appear, with access prevented until the actual declaration is reached; this is called the Temporal Dead Zone. The TDZ exists to prevent the sort of bugs that legacy hoisting can create.

在Javascript中,所有绑定的声明当控制流进入他们出现的作用域时被实例化。遗留的var和function声明允许在实际声明之前访问这些绑定的声明,值为undefined。这个遗留的问题被称为"hoisting"。let和const绑定的声明在控制流进入他们出现的作用域时也被实例化,但是有访问保护直到实际声明的时候,这称为临时性死区(TDZ)。TDZ的存在是为了防止这些提升所导致的bug

note

其实当control flow 进入一个scope的时候

(function () {
    console.log(a)
    console.log(b)
    console.log(typeof foo)
    var a 
    var b 
    function foo() {}
})()

例如a,b,foo这些变量和函数都会被实例化,使用var声明的变量和使用function声明的函数都允许在到实际声明的那行代码之前可以访问这些变量,但是value是undefined,ES6的let,const会有一个access prevented,必需到实际声明的那行代码之后才能去访问,否则会报ReferenceError,这也是为了防止因为hoisting而产生bug

你可能感兴趣的:(hoisting-vs-tdz)