ECMAScript 6 引入了许可声明。

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

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


当前回答

相反, var 可以像下面那样粘贴。 { console.log(cc); // undefined. 由于粘贴 var cc = 23; } { console.log(bb); // ReferenceError: bb 没有定义 let bb = 23; } 事实上, Per @Bergi, 两者都是粘贴。

其他回答

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

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.
var   --> Function scope  
let   --> Block scope
const --> Block scope

是的

在此样本中,你可以看到我被宣布在一个如果区块. 但它被宣布使用 var. 因此,它获得功能范围. 它意味着你仍然可以访问变量 i 内部函数 x. 因为 var 总是被推到函数. 尽管变量 i 被宣布在一个如果区块, 因为它使用 var 它被推到主函数 x。

函数 x(){ if(true){ var i = 100; } console.log(i); } x();

现在变量 i 被宣布在函数 y. 因此, i 被定义为函数 y. 您可以访问 i 内部函数 y. 但不是从外部函数 y。

let, const

让和 const 有区块范围。

但是,差异是,当你将值分配给 const 时,你不能再分配。

console.log(x); var x = 100;

console.log(x); // ERROR let x = 100;

在 MDN 中查看此链接

let x = 1;

if (x === 1) {
let x = 2;

console.log(x);
// expected output: 2
}

console.log(x);
// expected output: 1

“var”是函数分解,而“let”是区块分解。

您可以在函数中的任何地方使用变量,然后在函数中的任何地方使用变量,然后在函数中的任何地方使用变量。

或者你可以只是使用 Var 整个时间,因为你很不可能在一个函数内部发生范围冲突,然后你不需要跟踪你定义为允许或变量的变量。

有些人建议使用让所有时间,但这不是我的偏好,因为在许多其他编程语言的本地变量是功能的破坏,如果你使用其他,那么你可能会发现它更容易思考这个模式整个时间,而不是在使用JavaScript时更换。

const name = 'Max'; let age = 33; var hasHobbies = true; name = 'Maximilian'; age = 34; hasHobbies = false; const summarizeUser = (userName, userAge, userHasHobby) => { return ( 'Name is'+ userName + ', age is'+ userAge +'and the user has hobbies:'+ userHasHobby ); } console.log(summarizeUser(name, age, hasHobbies));

正如你可以从上面的代码运行中看到的那样,当你尝试更改 const 变量时,你会发现一个错误:

试图超越一个“名称”,这是一个恒定的。

TypeError: Invalid assignment to const 'name'.

但是,看看放变量。

首先,我们宣布让年龄=33岁,然后将另一个值年龄=34岁,这是OK;当我们试图改变时,我们没有任何错误。