let 语句允许您使用块作用域声明变量。
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
const 语句允许您声明常量(具有常量值的 JavaScript 变量)。
常量类似于 let 变量,但不能更改值。
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
1.实验一:
var i = 10;
(function() {
var i = 2;
})();
console.log(i);
// 结果: 10
let i = 10;
(function() {
let i = 2;
})();
console.log(i);
// 结果: 10
var i = 10;
(function() {
let i = 2;
})();
console.log(i);
//结果: 10
let i = 10;
(function() {
var i = 2;
})();
console.log(i);
//结果:10
let i = 10;
(function(){
i = 2;
})();
console.log(i);
//结果:2
var i = 10;
(function(){
i = 2;
})();
console.log(i);
//结果:2
以上可以看出let、var在日常使用中效果几乎一致,并不是很很多文章说的那样
下面再试一下官方说的块作用域
2.实验二:
var i = 10;
{
var i = 2;
}
console.log(i);
//结果:2
var i = 10;
{
let i = 2;
}
console.log(i);
//结果:10
let i = 10;
{
let i = 2;
}
console.log(i);
//结果:10
let i = 10;
{
var i = 2;
}
console.log(i);
// 报错
// SyntaxError: Identifier 'i' has already been declared
3.实验三:
{
var i = 10;
}
console.log(i);
//结果:10
{
let i = 10;
}
console.log(i);
// 报错:ReferenceError: i is not defined
(function(){
var i = 10;
})();
console.log(i);
//报错:ReferenceError: i is not defined
{
let i = 10;
console.log(i);
}
//结果:10
结论:let 和 var作用域不同,但在绝大部分可以通用,可以用let简化旧的闭包写法
Done.