简体   繁体   English

临时死区(ES6)似乎不起作用

[英]temporal dead zone (ES6) doesnt seem to work

Below is my code: 下面是我的代码:

<!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>

Its seems the temporal drop zone (TDZ) in es6 should throw a referenceError in case the let-var is used before it is declared. 似乎在es6中的临时拖放区(TDZ)应该抛出referenceError,以防在声明之前使用let-var。

However, in this example, I am getting undefined for let. 但是,在此示例中,我对let的定义变得不确定。 Where am i going wrong? 我要去哪里错了?

Been at this problem for a long time and wasted a day on this. 很久以来一直在解决这个问题,并为此浪费了一天。 (Any pointers would be very help). (任何指针都将非常有帮助)。 I am using Chrome v58. 我正在使用Chrome v58。

v58 has es6 compatibility as per https://kangax.github.io/compat-table/es6/ under current browser). 根据目前浏览器的https://kangax.github.io/compat-table/es6/,v58具有es6兼容性)。

I stripped off the traceur part and posted on babel-try it out, and got the same result. 我剥去了示踪剂部分,并贴上了通心粉试一下,得到了相同的结果。 在此处输入图片说明

Am wondering why is it not working in my chrome v58. 我想知道为什么我的Chrome v58无法正常工作。 Maybe it requires something else too?? 也许还需要其他东西吗?

You are using Traceur, which does not support TDZ for let/const . 您正在使用Traceur,它不支持TDZ的let / const It will convert let to var - making the TDZ behaviour for let identical to your var example. 它会转换letvar -制作用于让相同的变种例如TDZ行为。 Run the same code in an ES6-compatible environment and you'll see the expected result: 在与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'; }()); 

I removed the transpiler code and enabled the Experimental Features in JS chrome://flags/#enable-javascript-harmony here and it worked as expected now. 我删除了转译器代码,并在JS chrome:// flags /#enable-javascript-harmony中启用了实验性功能,现在可以正常使用了。

Chrome version v58 Chrome版本v58

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM