javascript 什么时候应该使用 let 和 var?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21906133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When should I use let and var?
提问by callumacrae
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.
显然,现在我应该始终使用var
关键字,因为let
并非所有东西都支持。
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?
当 let 关键字有更好的支持时(比如说,我在几年内编写了一个使用 Harmony 的 Node 应用程序),我什么时候应该使用let
关键字与var
关键字?
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".
我理解其中的区别 —var
用于函数作用域,而let
用于块作用域 — 但我正在寻找诸如“始终使用let
关键字”或“var
在函数顶部使用关键字,但块中的 let 关键字如 for 循环”之类的东西.
回答by neelsg
I would say that you should, as a principle, use let
whenever it is not inconvenient to do so. Such as:
我会说,作为原则,您应该let
在不方便的时候使用。如:
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
- 覆盖某些全局变量用于其他用途的风险较小
- 由于变量在变得无关紧要后长时间留在内存中而导致内存泄漏的风险降低
回答by Phil H
Use letas a general rule, and var on occasion.
一般使用 let,偶尔使用var 。
Block scoping is the standard and most readable choice, and will make debugging easier. Block scoping makes it easy to see exactly where a variable is in scope. Function scoping makes things a lot less apparent, and much easier to accidentally introduce bugs with scoping mistakes.
块作用域是标准的和最易读的选择,将使调试更容易。块作用域可以轻松查看变量在作用域中的确切位置。函数作用域使事情变得不那么明显,并且更容易意外引入具有作用域错误的错误。
In general, the smaller the scope you can use, the better. Thus let
over var
.
一般来说,您可以使用的范围越小越好。至此let
结束var
。
In particular, it helps deal with the endless problem of closing over variables and not realising their value will change before the closure is executed:
特别是,它有助于解决关闭变量的无休止的问题,并且在执行关闭之前没有意识到它们的值会改变:
for (var i = 1; i <= 5; i++) {
var item = document.createElement("LI");
item.appendChild(document.createTextNode("Item " + i));
let j = i;
item.onclick = function (ev) {
alert("Item " + j + " is clicked.");
};
list.appendChild(item);
}
回答by ooxi
Well the answer is quite simple use var
if you need function scoping and let
if you need block scoping.
好吧,var
如果您需要函数作用域并且let
需要块作用域,那么答案非常简单。