<> understand ES6 of let Attribute and var Differences between
<>let Introduction and of var Differences between
1.var No block level scope , and let Block level scope
2. stay js Only in function Has its own independent scope
If you don't understand :
for instance :
{var a=10} console.log(a);
1. When the web page is running a It can be printed directly
2. If will var change into let Time
{let a=10} console.log(a);
1. Console display a Undefined .
2. This shows let Has its own independent scope .
3. Since there is an independent scope , that let Can replace the function to solve the function closure problem .
for instance :
We use for Cycle as 5 Bind listening events with buttons. Click each button to print the corresponding number .
<body> <button>1</button> <button>2</button> <button>3</button> <button>4</
button> <button>5</button> </body> <script> var btn=document.
getElementsByTagName("button");// Get all button A list of for(var i=0;i<btn.length;i++){
btn[i].onclick=function(){console.log(i+1);} }
1. In this way, no matter which console we click, only the last number will be printed 5,
2. ahead 1234 It's all covered , Click that button to print 5
3. explain for of { } There is no block level scope
<> Previous solutions ( Function Closure )
for(var i=0;i<btn.length;i++){ (function a(i){ btn[i].onclick=function(){
console.log(i+1);} })(i); }
**
Close it with an immediate execution function , Then i Pass in the value of .( Not recommended )
<> The current solution (ES6 of let:var Upgraded version of )
Directly var change into let
for(let i=0;i<btn.length;i++){ btn[i].onclick=function(){console.log(i+1);} }
Solve the problem directly , Simple and convenient ( recommend !!!)
Study now js My classmate , Can develop the habit of writing let Relevant , It's also var Perfect version of !!!!!
Technology