ES6+核心特性
ES6(ECMAScript 2015)是 JavaScript 的革命性更新,引入了模块化、面向对象、异步处理等现代编程范式。
特性 | 作用 | 示例 | 解决痛点 |
---|---|---|---|
let/const | 块级作用域变量声明 | let x = 10; const PI = 3.14; | 变量提升、全局污染 |
箭头函数 | 简化函数语法 + 绑定this | const sum = (a, b) => a + b; | this 指向混乱 |
模板字符串 | 多行字符串 + 表达式嵌入 | `Hello ${name}!` | 字符串拼接繁琐 |
默认参数 | 函数参数默认值 | function log(msg = 'info') {...} | 参数判空冗余 |
解构赋值
const { name, age } = user;
const [first, second] = [10, 20]; // 数组解构
类型 | 特性 | 用例 |
---|---|---|
Set | 值唯一的集合 | new Set([1, 1, 2]) // {1, 2} |
Map | 键值对集合(键可任意类型) | map.set(objKey, value) |
WeakMap | 弱引用键(防内存泄漏) | 缓存私有数据 |
Class 语法
class Person {constructor(name) {this.name = name;}greet() {return `Hello, ${this.name}!`;}
}class Student extends Person {constructor(name, major) {super(name);this.major = major;}
}
模块化(Module)
// math.js
export const PI = 3.14;
export function sum(a, b) { return a + b; }// app.js
import { PI, sum } from './math.js';
Generator 函数
function* idGenerator() {let id = 0;while (true) yield id++;
}
const gen = idGenerator();
console.log(gen.next().value); // 0
扩展与元编程
特性 | 描述 | 示例 |
---|---|---|
Rest/Spread | 收集/展开元素 | const [a, ...rest] = [1,2,3] |
Symbol | 唯一标识符(防属性冲突) | const id = Symbol('id') |
Proxy | 对象操作拦截器 | 数据绑定、验证 |
Reflect | 对象操作的标准方法库 | Reflect.get(obj, 'key') |
ES6+ 演进时间线
版本 | 年份 | 关键特性 |
---|---|---|
ES2016 | 2016 | Array.prototype.includes |
ES2017 | 2017 | Async/Await , Object.values() |
ES2018 | 2018 | Promise.finally() , 异步迭代 |
ES2020 | 2020 | Optional Chaining (?.) , Nullish Coalescing (??) |
ES2023 | 2023 | findLast() , Hashbang 语法 |