ECMAScript 6 引入了许可声明。

我听说它被描述为一个当地变量,但我仍然不确定它是如何行为不同于 var 关键词。

什么是差异?什么时候应该被允许使用而不是 var?


当前回答

ECMAScript 6 添加了另一个关键字来宣布变量,而不是“放下”。

“Let”和“Let”在“var”上引入的主要目标是,而不是传统的词汇,区块点点点点点点点点点点点点点点点点点点点点点点点点。

其他回答

答答答答答答答答答答答答答答答答答

var 变量是全球性的,基本上可以到达到任何地方,而让变量不是全球性的,只有直到一个关闭的偏见杀死它们。

请参见下面的我的例子,并注意狮子(Let)变量如何在两个 console.logs 中以不同的方式行事;它在第二个 console.log 中变得无效。

var cat = "cat";
let dog = "dog";

var animals = () => {
    var giraffe = "giraffe";
    let lion = "lion";

    console.log(cat);  //will print 'cat'.
    console.log(dog);  //will print 'dog', because dog was declared outside this function (like var cat).

    console.log(giraffe); //will print 'giraffe'.
    console.log(lion); //will print 'lion', as lion is within scope.
}

console.log(giraffe); //will print 'giraffe', as giraffe is a global variable (var).
console.log(lion); //will print UNDEFINED, as lion is a 'let' variable and is now out of scope.

差异在于与每一个声明的变量范围。

让变量仅在其最接近的封锁区({... })中可见。让变量仅在变量被宣布后发生的代码线上可用。让变量不被随后的变量或变量重新宣布。让变量不被全球变量添加到全球窗口对象中。让变量易于使用与封锁(它们不会导致赛车条件)。

{
    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

正如我目前正在试图深入了解JavaScript,我将分享我的简短研究,其中包含一些已经讨论的伟大作品,以及一些其他细节,从不同的角度。

理解VAR和LAT之间的差异可以更容易,如果我们理解函数和区块范围之间的差异。

让我们来看看以下案例:

(function timer() {
    for(var i = 0; i <= 5; i++) {
        setTimeout(function notime() { console.log(i); }, i * 1000);
    }
})();


   Stack            VariableEnvironment //one VariablEnvironment for timer();
                                       // when the timer is out - the value will be the same for each iteration
5. [setTimeout, i]  [i=5] 
4. [setTimeout, i]  
3. [setTimeout, i]
2. [setTimeout, i]
1. [setTimeout, i]
0. [setTimeout, i]

####################    

(function timer() {
    for (let i = 0; i <= 5; i++) {
        setTimeout(function notime() { console.log(i); }, i * 1000);
    }
})();

   Stack           LexicalEnvironment - each iteration has a new lexical environment
5. [setTimeout, i]  [i=5]       
                      LexicalEnvironment 
4. [setTimeout, i]    [i=4]     
                        LexicalEnvironment 
3. [setTimeout, i]      [i=3]       
                         LexicalEnvironment 
2. [setTimeout, i]       [i=2]
                           LexicalEnvironment 
1. [setTimeout, i]         [i=1]
                             LexicalEnvironment 
0. [setTimeout, i]           [i=0]

当按时()被称为执行内容时,将创建一个内容,该内容将包含每个字符串的变量环境和所有相应的语法环境。

更简单的例子

功能范围

function test() {
    for(var z = 0; z < 69; z++) {
        //todo
    }
    //z is visible outside the loop
}

区块范围

function test() {
    for(let z = 0; z < 69; z++) {
        //todo
    }
    //z is not defined :(
}

简而言之,Let和Var之间的区别在于Var是功能分解,Let是区块分解。

这个解释是从我在Medium上写的一篇文章中得出的:

Hoisting 是一个 JavaScript 机制,在其中变量和函数声明被转移到其范围的顶部,由分数者将源代码列入一个中间代表性之前,实际的代码执行由 JavaScript 解释器开始。

// An array of adder functions.
var adderFunctions = [];

for (var i = 0; i < 1000; i++) {
  // We want the function at index i to add the index to its argument.
  adderFunctions[i] = function(x) {
    // What is i bound to here?
    return x + i;
  };
}

var add12 = adderFunctions[12];

// Uh oh. The function is bound to i in the outer scope, which is currently 1000.
console.log(add12(8) === 20); // => false
console.log(add12(8) === 1008); // => true
console.log(i); // => 1000

// It gets worse.
i = -8;
console.log(add12(8) === 0); // => true

上面的过程不会产生所需的函数序列,因为我的范围超越了每个函数创建的区块的 iteration。 相反,在环节结束时,每个函数的 i 关闭指在环节结束时的 i 值(1000)为每个在 adder 中的匿名函数。

// Let's try this again.
// NOTE: We're using another ES6 keyword, const, for values that won't
// be reassigned. const and let have similar scoping behavior.
const adderFunctions = [];

for (let i = 0; i < 1000; i++) {
  // NOTE: We're using the newer arrow function syntax this time, but 
  // using the "function(x) { ..." syntax from the previous example 
  // here would not change the behavior shown.
  adderFunctions[i] = x => x + i;
}

const add12 = adderFunctions[12];

// Yay! The behavior is as expected. 
console.log(add12(8) === 20); // => true

// i's scope doesn't extend outside the for loop.
console.log(i); // => ReferenceError: i is not defined

每个函数现在保留在函数创建时的 i 的值,并且 adderFunctions 按照预期行事。

现在,图像将两种行为混合在一起,你可能会看到为什么不建议在同一脚本中混合更新的Let和 const。

const doubleAdderFunctions = [];

for (var i = 0; i < 1000; i++) {
    const j = i;
    doubleAdderFunctions[i] = x => x + i + j;
}

const add18 = doubleAdderFunctions[9];
const add24 = doubleAdderFunctions[12];

// It's not fun debugging situations like this, especially when the
// code is more complex than in this example.
console.log(add18(24) === 42); // => false
console.log(add24(18) === 42); // => false
console.log(add18(24) === add24(18)); // => false
console.log(add18(24) === 2018); // => false
console.log(add24(18) === 2018); // => false
console.log(add18(24) === 1033); // => true
console.log(add24(18) === 1030); // => true

不要让这件事发生在你身上,使用灯具。