Skip to content

Instantly share code, notes, and snippets.

@Caisen1988
Last active September 3, 2020 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Caisen1988/0adcb92167c94fe2a3ab7569ef70a3f5 to your computer and use it in GitHub Desktop.
Save Caisen1988/0adcb92167c94fe2a3ab7569ef70a3f5 to your computer and use it in GitHub Desktop.
//let也不允许同一个块作用域中出现冗余声明。这样会导致报错
var name;
var name;
let age;
let age; // SyntaxError;标识符age已经声明过了
//JavaScript引擎会记录用于变量声明的标识符及其所在的块作用域,因此嵌套使用相同的标识符不会报错,而这是因为同一个块中没有重复声明:
var name = 'Nicholas';
console.log(name); // 'Nicholas'
if (true) {
var name = 'Matt';
console.log(name); // 'Matt'
}
let age = 30;
console.log(age); // 30
if (true) {
let age = 26;
console.log(age); // 26
}
//let与var的另一个重要的区别,就是let声明的变量不会在作用域中被提升。
// name会被提升
console.log(name); // undefined
var name = 'Matt';
// age不会被提升
console.log(age); // ReferenceError:age没有定义
let age = 26;
//与var关键字不同,使用let在全局作用域中声明的变量不会成为window对象的属性(var声明的变量则会)
var name = 'Matt';
console.log(window.name); // 'Matt'
let age = 26;
console.log(window.age); // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment