ECMAScript 6 引入了许可声明。
我听说它被描述为一个当地变量,但我仍然不确定它是如何行为不同于 var 关键词。
什么是差异?什么时候应该被允许使用而不是 var?
ECMAScript 6 引入了许可声明。
我听说它被描述为一个当地变量,但我仍然不确定它是如何行为不同于 var 关键词。
什么是差异?什么时候应该被允许使用而不是 var?
当前回答
下面是让关键词的解释,有几个例子。
主要区别在于,一个变量的范围是整个关闭功能。
此图在维基百科上显示哪些浏览器支持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;
下面是两者之间的区别的例子:
正如你可以看到的那样, var j 变量仍然在 loop 范围之外有一个值(区块范围),但 let i 变量在 loop 范围之外是不确定的。
“使用严格”; console.log(“var:”); for (var j = 0; j < 2; j++) { console.log(j); } console.log(j); console.log(“let:”); for (let i = 0; i < 2; i++) { console.log(i); } console.log(i);
使用 var 声明定义的变量在其定义的整个函数中已知,从函数的开始。 (*) 使用 let 声明定义的变量仅在其定义的区块中已知,从其定义的时刻开始。
// i IS NOT known here
// j IS NOT known here
// k IS known here, but undefined
// l IS NOT known here
function loop(arr) {
// i IS known here, but undefined
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
for( var i = 0; i < arr.length; i++ ) {
// i IS known here, and has a value
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
};
// i IS known here, and has a value
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
for( let j = 0; j < arr.length; j++ ) {
// i IS known here, and has a value
// j IS known here, and has a value
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
};
// i IS known here, and has a value
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
}
loop([1,2,3,4]);
for( var k = 0; k < arr.length; k++ ) {
// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS NOT known here
};
for( let l = 0; l < arr.length; l++ ) {
// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS known here, and has a value
};
loop([1,2,3,4]);
// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS NOT known here
今天使用安全吗?
有些人会说,在未来,我们只会使用让陈述,而这些陈述会变得过时。JavaScript老师Kyle Simpson写了一篇非常复杂的文章,他认为为什么不会这样。
事实上,我们实际上需要问自己是否安全使用放弃声明,这个问题的答案取决于你的环境:
此分類上一篇
如何跟踪浏览器支持
这个解释是从我在Medium上写的一篇文章中得出的:
Hoisting 是一个 JavaScript 机制,在其中变量和函数声明被转移到其范围的顶部,由分数者将源代码列入一个中间代表性之前,实际的代码执行由 JavaScript 解释器开始。
函数运行() { var foo = “Foo”; let bar = “Bar”; console.log(foo, bar); // Foo Bar { var Moo = “Mooo” let baz = “Bazz”; console.log(moo, baz); // Mooo Bazz } console.log(moo); // Mooo console.log(baz); // ReferenceError } run();
為什麼讓關鍵字被引入到語言是功能範圍是混亂的原因,是JavaScript的主要錯誤來源之一。
创建全球对象财产
在最高层次上,让我们不同于VAR,不会在全球对象上创造任何财产:
var foo = “Foo”; // 全球推翻的Let bar = “Bar”; // 不允许全球推翻的console.log(window.foo); // Foo console.log(window.bar); // undefined