所以。。到底什么是TDZ?
TDZ 是 Temporal Dead Zone 的縮寫,翻譯過來就是時(shí)間死區(qū)。
什么是時(shí)間死區(qū)呢?
我的理解就是一個(gè)變量晋控,從定義到被賦值的中間這段時(shí)間就成為時(shí)間死區(qū)。如果你的console.log是在時(shí)間死區(qū)里姓赤,那么就會報(bào)錯(cuò)赡译。
console.log(aLet) // would throw ReferenceError
let aLet;
console.log(aLet); // undefined
aLet = 10;
console.log(aLet); // 10
上述代碼中,在aLet 被復(fù)制 10 之前不铆,就被稱為時(shí)間死區(qū)蝌焚。
let x = 'outer value';
(function() {
// start TDZ for x
console.log(x);
let x = 'inner value'; // declaration ends TDZ for x
}());
那么問題來了,如果我的代碼寫成下面這樣.
var a = 1
function test(a=a){
console.log(a)
}
test()
居然報(bào)錯(cuò)了誓斥。只洒。。
這是如果參數(shù)存在默認(rèn)值岖食,那就出現(xiàn)了第三種作用域parameters environment(參數(shù)作用域)红碑。
在上述代碼中的參數(shù)作用域中舞吭,a=a 相當(dāng)于 let a =a ,他會去找自己內(nèi)部定義的a的值泡垃,但是這時(shí)候a還處于TDZ中,所以會報(bào)出 a is not defined 的錯(cuò)誤羡鸥。
那么參數(shù)作用域可以訪問函數(shù)作用域么蔑穴?
function test(a = b){
var b =1
console.log(a)
}
test()
又報(bào)出了b is not defined的錯(cuò)誤。
說明參數(shù)作用域既訪問不了全局作用域惧浴,也訪問不了函數(shù)作用域存和。
引用:
http://www.reibang.com/p/ebc51ce05416
https://github.com/ruanyf/es6tutorial/blob/eb2a62215a7bc4f73ac08ac29a90a248a48193ea/docs/function.md
http://code.wileam.com/default-value-n-params-env/
http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified/