变量和常量
let
用于声明变量
特性:
- 类似var, 但定义的变量仅仅在代码块内有用
- 不存在变量提升,所有一定要声明后使用
- 应用于局部变量、for循环
// 作用域
{
var a = 1;
console.log(a); // 1
let b = 2;
console.log(b); // 2
}
console.log(a) // 1
console.log(b) // error: b is not defined
for (let i = 0; i < 3; i++)
console.log(i); // 1 2 3
console.log(i) // error: i is not defined
{
// 不存在变量提升
// 块级作用域内lei变量会形成封闭式死区,一旦出现,在声明前是不可用的
if (true) {
tmp = 'abc';
let tmp;
console.log(tmp); // undefined
tmp = 'def';
console.log(tmp); // def
}
}
{
// 比较隐蔽的死区
function bar (x=2, y=x) {
console.log(x, y); // 正常执行
}
function bar (x=y, y=2) {
console.log(x, y); // undefned, 2
}
bar();
}
{
let a = 10;
// 下面3种方式声明都会报错
// Duplicate declararion 'a'
// var a = 1;
// let a = 1;
// const a = 1;
}
const
用于声明常量
特性:
- 基本特性跟let一样
- 声明时必须初始化
- 一旦声明不可更改
- 前置export可声明跨模块的常量(import)
{
// 声明必须初始化
const foo; // error: Unexpeted token
// 一旦声明不可更改
const a = 1;
a = 2; // error: "a" is read-only
}
{
// 对于复合型的常量 const只保证引用地址不变 内容可变
const foo1 = {};
foo1.name = 'ES6';
console.log(foo1); // {name: "ES6"}
foo1 = { // error: "foo" is read-only
name: 'ES6'
}
// 如果想将对象冻结,可使用Object.freeze()
const foo2 = Object.freeze({name: 'ES6'});
// error: Can't add property name, object is not extensible
foo.name = 'zhangsan'
// 用于声明跨模块的常量
// import {A, B, C} from '...'
// import * as params from '...'
// params.A => 1 ...
export const A = 1;
export const B = 2;
export const C = 3;
}