ES6 什么是块级作用域变量
在ES5中,当我们使用var关键字 声明变量时,变量的作用域要么是全局的,要么是局部的。
- 全局变量: 当我们在函数外部声明变量时。
- 局部变量: 当我们在函数内部声明变量时。
但是,在ECMAScript 2015(ES6)中引入了两个新的关键字let 和const ,这两个关键字在JavaScript中提供了块级作用域。所有在大括号{ }中声明的变量都限制在该块及其内部块中访问。我们无法访问该块外部的变量,否则会抛出引用错误(变量未定义),或者如果在全局作用域中有同名变量,则会引用那个变量。
let关键字: 使用var 关键字声明的变量可以重新声明,但是在同一块内 声明的变量不能重新声明。这将抛出SyntaxError: Identifier has already been declared。
示例1: 在这个示例中,我们将使用let关键字重新定义变量。
Javascript
function valueAssign() {
let x = 10;
var z = 15;
if (true) {
let y = 5;
console.log(y); // Here y is 5
console.log(x); // Here x is 10
console.log(z); // Here z is 15
}
console.log(x); // Here x is 10
console.log(z); // Here z is 15
console.log(y); // ReferenceError: y is not defined
}
valueAssign();
输出:
5
10
15
10
15
ReferenceError: y is not defined
在这里,我们看到x和z都是在外部块中声明的,并且参考了if的块{},而y声明在内部块中。这里使用了var关键字声明z,所以我们可以在valueAssign()函数中的任何地方使用z变量,因为使用var关键字声明的变量不能具有块作用域。但是,x和y都使用let关键字进行声明。x在外部块中声明,所以我们可以在内部块中使用x。由于y在内部块中声明,所以我们不能在外部块中使用它。let和const将在我声明的块上工作,并且将在其中的块上工作。因此,当我们在外部块中打印y时,会出错。
示例2: 在此示例中,我们将看到使用var 和let 重新声明变量的工作原理:
Javascript
// Redeclared using var
function valueAssignWithVar() {
var y = 20;
y = 30; // Redeclare allowed
console.log(y);
}
// Redeclared using let in different block
function valueAssignWithLet1() {
let x = 20;
if (true) {
let x = 5; // Redeclare allowed
console.log(x);
}
console.log(x);
}
// Redeclared using let in same block
function valueAssignWithLet2() {
let x = 10;
let x = 5; // Redeclare not allowed
// SyntaxError: Identifier 'x' has
// already been declared
console.log(x);
}
valueAssignWithVar();
valueAssignWithLet1();
valueAssignWithLet2();
输出:
30
5
20
SyntaxError: Identifier 'x' has already been declared
const关键字 :使用const 关键字声明的变量严禁在同一块 内重新声明和重新赋值。当你不希望在整个程序中改变该变量的值时,我们使用const 关键字。
示例1: 在这个示例中,我们将看到使用const 重新分配变量的工作原理。
JavaScript
// Reassigned not allowed
const x = 10;
x = 5; // TypeError: Assignment to constant variable
console.log(x);
输出:
TypeError: Assignment to constant variable.
示例2: 在这个示例中,我们将看到使用const 重新声明变量的工作方式。
Javascript
// Redeclared using const in different block
function valueAssignWithConst1() {
const x = 20;
if (true) {
const x = 5; // Redeclare allowed
console.log(x);
}
console.log(x);
}
// Redeclared using const in same block
function valueAssignWithConst2() {
const x = 10;
const x = 5; // Redeclare not allowed
// SyntaxError: Identifier 'x' has
// already been declared
console.log(x);
}
valueAssignWithConst1();
valueAssignWithConst2();
输出结果:
SyntaxError: Identifier 'x' has already been declared
示例3: 在这个示例中,我们将看到使用const 的块作用域的工作方式。
JavaScript
function valueAssign() {
const x = 10;
var z = 15;
if (true) {
const y = 5;
console.log(y); // Here y is 5
console.log(x); // Here x is 10
console.log(z); // Here z is 15
}
console.log(x); // Here x is 10
console.log(z); // Here z is 15
console.log(y); // Error: y is not defined
}
valueAssign();
输出:
5
10
15
10
15
ReferenceError: y is not defined
极客教程