什么时候应该使用let和var? [英] When should I use let and var?
问题描述
编辑:请阅读问题!我已经知道差异了这不是重复的。
显然,现在我应该始终使用 var
在$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $在几年的时间内编写一个使用Harmony的Node应用程序),何时应该使用 let
关键字vs var
关键字?
我了解差异 - var
用于函数范围,而 let
是用于块的范围 - 但是我正在寻找类似总是使用 let
关键字或使用 var
关键字在函数的顶部,但let for循环中的let关键字。
我会说,作为一个原则,你应该使用 let
,只要不是不方便这样做。例如:
for(let i = 0; i< 100; i ++){
//做某事
}
if(condition){
let msg = a + b + c;
console.log(msg);
alert(msg);
}
这种方法的优点是:
- 减少一些全局变量用于其他东西的风险较小
- 由于变量在存储器中长时间存在,内存泄漏的风险降低变得无关紧要
EDIT: Please read the question! I already know the difference. This is not a duplicate.
Obviously, right now I should always be using the var
key word as let
isn't supported in everything.
When the let keyword has better support (say, I'm writing a Node application in a couple years time which uses Harmony), when should I use the let
keyword vs the var
keyword?
I understand the difference —var
is for function scoping while let
is for block scoping—but I'm looking for something like "always use the let
keyword" or "use the var
keyword at the top of functions, but the let keyword in blocks like for loops".
I would say that you should, as a principle, use let
whenever it is not inconvenient to do so. Such as:
for (let i = 0; i < 100; i++) {
// Do something
}
if (condition) {
let msg = a + b + c;
console.log(msg);
alert(msg);
}
The advantages to this approach is:
- Less risk of overriding some global variable use for something else
- Less risk of memory leaks due to variables staying in memory long after they have become irrelevant
这篇关于什么时候应该使用let和var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!