2017-06-05 35 views
1

下面是我的代碼:時間死區(ES6)似乎沒有工作

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Title</title> 

</head> 
<body> 
<h1 id="message"></h1> 

<script src="traceur/traceur.js"></script> 
<script src="traceur/BrowserSystem.js"></script> 
<script src="traceur/bootstrap.js"></script> 
<script type="module"> 

    var x = 'outer scope'; 
    (function() { 
     console.log(x); //Expected undefined, got undefined ! this is as expected. 
     var x = 'inner scope'; 
    }()); 

    //same as above, but changed to var to let and x to y 
    let y = 'outer scope'; 
    (function() { 
     console.log(y); //Was expecting ReferenceError here, but got undefined. WTF ??!!! 
     let y = 'inner scope'; 
    }()); 


</script> 

</body> 
</html> 

它似乎ES6時間放置區(TDZ)應該拋出的ReferenceError萬一讓-VAR之前它使用被宣佈。

但是,在這個例子中,我沒有定義讓。 我哪裏錯了?

一直在這個問題很長一段時間,浪費了一天的時間。 (任何指針都會非常有幫助)。我使用的是Chrome v58。

v58在當前瀏覽器下具有esp兼容性,按照https://kangax.github.io/compat-table/es6/)。

我剝離traceur部分並貼在babel上 - 試用它,並得到相同的結果。 enter image description here

我想知道爲什麼它不能在我的鍍鉻v58中工作。也許它還需要別的東西?

+0

僅供參考,它被稱爲* temporal ** dead ** zone *,而不是時間* drop * zone。 –

回答

0

您正在使用Traceur,其中does not support TDZ for let/const。它會將let轉換爲var - 使TDZ行爲與let var相同。在ES6兼容環境中運行相同的代碼,你會看到預期的結果:

var x = 'outer scope'; 
 
(function() { 
 
    console.log(x); 
 
    var x = 'inner scope'; 
 
}()); 
 

 
let y = 'outer scope'; 
 
(function() { 
 
    console.log(y); 
 
    let y = 'inner scope'; 
 
}());

+0

您使用的是哪種瀏覽器及其版本?我評估了我的Chrome v 58並使用kangax.github.io/compat-table/es6(在當前瀏覽器下),看起來它與ES6兼容。 – Plankton

+0

鉻58也。您是否點擊了上面的* Run code snippet *按鈕?應該在下面顯示正確的結果 – CodingIntrigue

+0

是的,我看到了。但想知道爲什麼它不能在我的Chrome瀏覽器v 58中正常工作。在babel上嘗試過,試試看,我得到的結果相同。未定義。這是錯誤的 – Plankton

0

我刪除了transpiler代碼和JS啓用了實驗性的功能 鉻://標誌/#enable-javascript-harmony在這裏,它現在按預期工作。

Chrome版本v58