let和var的区别
2017-10-16 本文已影响38人
胡思乱想的Alice
let和var的区别
1 let声明的变量有块作用域
if(!'a' in window){var a=1} console.log(a);
undefined //变量提升
if(!'a' in window){let a=1} console.log(a)
VM75:1 Uncaught ReferenceError: a is not defined
at <anonymous>:1:41 //a只存在于块作用域内
2 let声明的全局变量不是全局对象的属性
let a=123
window.a
//undefined
var b=345
window.b
//345
3 重复定义let变量会报错
let x=123
var x=123
//VM217:1 Uncaught SyntaxError: Identifier 'x' has already been declared
at <anonymous>:1:1
var y=345
let y=345
//VM245:1 Uncaught SyntaxError: Identifier 'y' has already been declared
at <anonymous>:1:1
var z=678
var z=789
z
//789
4 for循环中的let每次迭代时都为i创建新的绑定。
var声明全局变量i,循环内过度共享i变量
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1500);
}
let声明的变量每次迭代都为i创建新的绑定
for (let i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1500);
}