ECMAScript 6 引入了许可声明。
我听说它被描述为一个当地变量,但我仍然不确定它是如何行为不同于 var 关键词。
什么是差异?什么时候应该被允许使用而不是 var?
ECMAScript 6 引入了许可声明。
我听说它被描述为一个当地变量,但我仍然不确定它是如何行为不同于 var 关键词。
什么是差异?什么时候应该被允许使用而不是 var?
当前回答
主要差异是范围差异,而让它只能在所宣布的范围内可用,如在圆圈中,可在圆圈之外可访问,例如从MDN的文档(MDN的例子):
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}`
var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined
当在区块内使用时,请将变量的范围限制在该区块上。
var a = 1;
var b = 2;
if (a === 1) {
var a = 11; // the scope is global
let b = 22; // the scope is inside the if-block
console.log(a); // 11
console.log(b); // 22
}
console.log(a); // 11
console.log(b); // 2
其他回答
下面是让关键词的解释,有几个例子。
主要区别在于,一个变量的范围是整个关闭功能。
此图在维基百科上显示哪些浏览器支持JavaScript 1.7.
请注意,只有 Mozilla 和 Chrome 浏览器支持它. IE、Safari 和其他可能不支持它。
显然,至少在Visual Studio 2015中,TypeScript 1.5,“var”允许一个区块中的相同变量名称的多个声明,而“Let”不。
这不会导致编译错误:
var x = 1;
var x = 2;
这将是:
let x = 1;
let x = 2;
差异在于与每一个声明的变量范围。
让变量仅在其最接近的封锁区({... })中可见。让变量仅在变量被宣布后发生的代码线上可用。让变量不被随后的变量或变量重新宣布。让变量不被全球变量添加到全球窗口对象中。让变量易于使用与封锁(它们不会导致赛车条件)。
{
let x = 1;
}
console.log(`x is ${x}`); // ReferenceError during parsing: "x is not defined".
{
x = x + 1; // ReferenceError during parsing: "x is not defined".
let x;
console.log(`x is ${x}`); // Never runs.
}
没有重新宣言:下列代码表明,被允许宣言的变量不能随后重新宣言:
let x = 1;
let x = 2; // SyntaxError: Identifier 'x' has already been declared
var button = "I cause accidents because my name is too common.";
let link = "Though my name is common, I am harder to access from other JS files.";
console.log(link); // OK
console.log(window.link); // undefined (GOOD!)
console.log(window.button); // OK
5. 易于使用与关闭: 与 var 表示的变量与关闭内部的关闭工作不太好. 这里是一个简单的旋转,结果的值序列,变量 i 有在不同的时间点:
for (let i = 0; i < 5; i++) {
console.log(`i is ${i}`), 125/*ms*/);
}
具体而言,这些输出:
i is 0
i is 1
i is 2
i is 3
i is 4
在JavaScript中,我们经常使用变量比它们创建时更晚的时间。当我们通过延迟输出以关闭转移到设置Timeout时:
for (let i = 0; i < 5; i++) {
setTimeout(_ => console.log(`i is ${i}`), 125/*ms*/);
}
for (var i = 0; i < 5; i++) {
setTimeout(_ => console.log(`i is ${i}`), 125/*ms*/);
}
i is 5
i is 5
i is 5
i is 5
i is 5
主要差异是范围差异,而让它只能在所宣布的范围内可用,如在圆圈中,可在圆圈之外可访问,例如从MDN的文档(MDN的例子):
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}`
var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined
当在区块内使用时,请将变量的范围限制在该区块上。
var a = 1;
var b = 2;
if (a === 1) {
var a = 11; // the scope is global
let b = 22; // the scope is inside the if-block
console.log(a); // 11
console.log(b); // 22
}
console.log(a); // 11
console.log(b); // 2
有一些微妙的差异 - 让滑动行为更像变量滑动在更多或更少的任何其他语言。
例如,它转向封锁区块,它们在被宣布之前不存在,等等。
然而,值得注意的是,让它只是新的JavaScript实施的一部分,并且有不同的浏览器支持程度。