ES6(ECMAScript 2015)主要特性一览
下面按“语法糖”“新数据类型/API”“异步 & 迭代”三大类,总结 ES6 的核心要点。
---
## 一、语法糖
- 块级作用域:`let`、`const`
- `let`:声明块级变量,不可重复声明,不存在变量提升
- `const`:声明常量,必须初始化、且引用不可变
- 模板字符串(Template Literals)
```js
const name = 'Alice';
console.log(`Hello, ${name}!`);
```
- 解构赋值
- 数组解构:
```js
const [a, , b = 2] = [1, , 3];
```
- 对象解构:
```js
const {x, y: aliasY = 0} = {x: 10};
```
- 箭头函数(Arrow Functions)
- 语法简洁,自动绑定父级 `this`
```js
const sum = (a, b) => a + b;
```
- 默认参数、剩余参数、扩展运算符
```js
function foo(a = 1, ...rest) { /* ... */ }
const arr2 = [...arr1, 4, 5];
```
- 对象字面量增强
- 属性简写、方法简写、计算属性名
```js
const x = 1;
const obj = {
x,
['prop_' + x]: 42,
greet() { console.log('hi'); }
};
```
- `class` + `extends` + `super`
- 基于原型的“糖”,更接近传统 OOP 语法
```js
class Animal {
constructor(name) { this.name = name; }
speak() { console.log(this.name); }
}
class Dog extends Animal {
bark() { console.log('Woof'); }
}
```
---
## 二、新的数据类型/API
- Symbol
- 新的原始类型,常用作对象的“私有”键
```js
const uid = Symbol('id');
obj[uid] = 123;
```
- Map、Set、WeakMap、WeakSet
- 原生键值对 & 去重容器
```js
const map = new Map([[keyObj, 'value']]);
const set = new Set([1,2,2,3]); // {1,2,3}
```
- Promise
- 原生的异步控制方案
```js
fetch(url)
.then(res => res.json())
.catch(err => console.error(err));
```
- 模块化(Modules)
- `export` / `import`
```js
// lib.js
export function fn() { /*...*/ }
// app.js
import { fn } from './lib.js';
```
- Reflect、Proxy
- Reflect:类似 `Object.*` 的补充
- Proxy:拦截对象操作,做元编程
```js
const p = new Proxy(target, {
get(obj, prop) { /* 拦截读取 */ }
});
```
---
## 三、异步 & 迭代
- 生成器(Generator)
- `function*` + `yield`,可暂停/恢复
```js
function* gen() {
yield 1;
yield 2;
return 3;
}
```
- Iterable & Iterator
- 支持 `for…of`、扩展运算符遍历
```js
for (const v of [1,2,3]) { /* ... */ }
```
- `for…of`
- 针对可迭代对象,更友好地遍历索引/键值对
---
### 小结
ES6 是一次大版本更新,引入了**模块化**、**类**、**Promise**、**生成器**、**Proxy** 等核心概念,并大幅增强了**语法糖**(解构、模板、箭头函数等),让 JavaScript 编写更简洁、可维护、符合现代工程化需求。