es6 新关键字let

let提供了另一种变量生命的方式。let关键字可以将变量绑定到所在的任意作用于中(通常 {}内部)。换句话说,ley为其声明的变量作用在了块作用域。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title></title>
 5     <script type="text/javascript">
 6         window.onload=function(){
 7             var list=document.getElementById("list");
 8             for(let i=0;i<5;i++){
 9                 var item=document.createElement("li");
10                 item.appendChild(document.createTextNode("item"+i));
11                 
12                 item.onclick=function(ev){
13                     console.log("item"+i+"is clicked");
14                 };
15                 list.appendChild(item);
16             }
17         }
18     </script>
19 </head>
20 <body>
21     <ul id="list">
22         
23     </ul>
24 </body>
25 </html>

上面的代码如果换成了var i=0 那么点击只会出现item5 is clicked。然而用let 可以正常打印。因为如果换成var的话是函数级的变量,而let让他有了块作用域,指向了5个不同了内部函数。

let  对比 var

let的作用域是块,而var的作用域是函数

var a = 5;
var b = 10;

if (a === 5) {
  let a = 4; // The scope is inside the if-block
  var b = 1; // The scope is inside the function

  console.log(a);  // 4
  console.log(b);  // 1
} 

console.log(a); // 5
console.log(b); // 1

let 在循环中

可以用 let 来代替 var ,在 for 定义块中使用块级变量.

for (let i = 0; i < 10; i++) {
  console.log(i); // 0, 1, 2, 3, 4 ... 9
}

console.log(i); // i is not defined

 

原文地址:https://www.cnblogs.com/ybleeho/p/7596161.html