ECMAScript 6 引入了许可声明。
我听说它被描述为一个当地变量,但我仍然不确定它是如何行为不同于 var 关键词。
什么是差异?什么时候应该被允许使用而不是 var?
ECMAScript 6 引入了许可声明。
我听说它被描述为一个当地变量,但我仍然不确定它是如何行为不同于 var 关键词。
什么是差异?什么时候应该被允许使用而不是 var?
当前回答
函数 VS 区块范围:
与 var 和 let 的主要区别是,与 var 宣言的变量是函数分解的,而与 let 宣言的函数是区块分解的。
function testVar () {
if(true) {
var foo = 'foo';
}
console.log(foo);
}
testVar();
// logs 'foo'
function testLet () {
if(true) {
let bar = 'bar';
}
console.log(bar);
}
testLet();
// reference error
// bar is scoped to the block of the if statement
当第一个函数测试Var 被称为变量 foo 时,与 var 声明,仍然在 if 声明之外可用。
与Let的变量:
当第二个函数测试Let被称为变量栏,用Let表示,仅可在 if 声明中访问,因为用Let表示的变量是区块分开的(其中一个区块是曲线条之间的代码,例如,如果{},为{},函数{})。
请不要让变量变量:
变量与不要被抓住:
console.log(letVar);
let letVar = 10;
// referenceError, the variable doesn't get hoisted
与 var do 相容的变量:
console.log(varVar);
var varVar = 10;
// logs undefined, the variable gets hoisted
var bar = 5;
let foo = 10;
console.log(bar); // logs 5
console.log(foo); // logs 10
console.log(window.bar);
// logs 5, variable added to window object
console.log(window.foo);
// logs undefined, variable not added to window object
其他回答
下面是让关键词的解释,有几个例子。
主要区别在于,一个变量的范围是整个关闭功能。
此图在维基百科上显示哪些浏览器支持JavaScript 1.7.
请注意,只有 Mozilla 和 Chrome 浏览器支持它. IE、Safari 和其他可能不支持它。
下面是两者之间的区别的例子:
正如你可以看到的那样, 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);
一些黑客与Let:
1。
let statistics = [16, 170, 10];
let [age, height, grade] = statistics;
console.log(height)
二。
let x = 120,
y = 12;
[x, y] = [y, x];
console.log(`x: ${x} y: ${y}`);
3、
let node = {
type: "Identifier",
name: "foo"
};
let { type, name, value } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // undefined
let node = {
type: "Identifier"
};
let { type: localType, name: localName = "bar" } = node;
console.log(localType); // "Identifier"
console.log(localName); // "bar"
Getter 和 Setter 與 Let:
let jar = {
numberOfCookies: 10,
get cookies() {
return this.numberOfCookies;
},
set cookies(value) {
this.numberOfCookies = value;
}
};
console.log(jar.cookies)
jar.cookies = 7;
console.log(jar.cookies)
有一些微妙的差异 - 让滑动行为更像变量滑动在更多或更少的任何其他语言。
例如,它转向封锁区块,它们在被宣布之前不存在,等等。
然而,值得注意的是,让它只是新的JavaScript实施的一部分,并且有不同的浏览器支持程度。
在 MDN 中查看此链接
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1