首页 > 其他 > 详细

[ES6] 03. The let keyword -- 1

时间:2014-11-19 23:57:14      阅读:517      评论:0      收藏:0      [点我收藏+]
var message = "Hi";
{
   var message = "Bye";       
}

console.log(message); 

//Bye

The message inside the block still has impact on the outside.

 

If you add function around the inside message:

var message = "Hi";

function greeting(){
    var message = "Bye";
}

console.log(message);

//Hi

Then "Bye" message has no impact on the "Hi" message.

But if create something like "for", "while" loop and if block, you will still get the "Bye";

 

Let


 

To help with this problem, we do have LET in ES6, which will allow me to use block scoping.

let message = "Hi";
{
    let message = "Bye";
}

console.log(message);

//Hi

This "Bye" message, because it‘s inside of a block, even though it‘s not inside of a function, has no impact on the assignment of this message. They are two separate and different entities.

 

Let in For Loop:


 

Recall one problem code:

var fs = [];

for(var i = 0; i < 10; i++){
    fs.push(function(i){
         console.log(i)   
    });
}

fs.forEach(function(f){
    f();
});

//10
//10
...
//10

The output will be 10 all the time.

 

If we swtich var to let:

var fs = [];

for(let i = 0; i < 10; i++){
    fs.push(function(i){
         console.log(i)   
    });
}

fs.forEach(function(f){
    f();
});

//0
//1
...
//9

Then the output is 0-9. The reason for that is because, let keyword each time it create a new instance in for loop.

 

What this really means in the end is that if you‘re used to bringing your variables up to the top of a scope using VAR and things like VAR i, VAR temp, where you want to be careful, because you‘re afraid of wasting behaviors due to this i.

function varFun(){
    
    var previous = 0;
    var current = 1;
    var i;
    var temp;

    for(i = 0; i < 10; i++){
          temp = previous;
          previous = current;
          current = temp + current;
    }
}


function letFun(){

    let previous = 0;
    let current = 1;

    for(let i = 0; i < 10; i++){
        let temp = previous;
        previous= current;
        current = temp + current;
    }
}

Feel free now to use the LET keyword, and instead of declaring it at the top, you can declare it in line, inside of the FOR statement, as well as declaring it inside of the FOR block, and it‘ll safely create this temp each time it goes through the FOR block.

[ES6] 03. The let keyword -- 1

原文:http://www.cnblogs.com/Answer1215/p/4109464.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!