ES6(ECMAScript 2015)是 JavaScript 语言发展史上的一个重要里程碑,它引入了许多新的语法特性和功能,提升了代码的可读性、可维护性和开发效率。
ES6 引入了 let
和 const
关键字,用于声明块级作用域的变量,解决了 var 的变量提升和全局污染问题。
// let 示例:块级作用域
function testLet() {
if (true) {
let x = 10;
}
console.log(x); // 报错:x 未定义
}
// const 示例:常量声明
const PI = 3.14159;
PI = 3.14; // 报错:无法重新赋值给常量
关键点:
let
允许变量重新赋值,但不能重复声明const
声明常量,必须初始化且不能重新赋值{}
内有效)箭头函数提供了更简洁的函数语法,并且自动绑定 this
上下文。
// 基本语法
const sum = (a, b) => a + b;
// 多行表达式需要大括号和 return
const multiply = (a, b) => {
return a * b;
};
// 无参数时使用空括号
const sayHello = () => console.log('Hello!');
// 自动绑定 this
class Counter {
constructor() {
this.count = 0;
}
increment = () => {
this.count++; // 箭头函数保留 this 上下文
}
}
优势:
function
和 return
关键字this
,继承自父级作用域模板字符串使用反引号(`),支持变量插值和多行字符串。
const name = 'Alice';
const age = 30;
// 变量插值
const greeting = `Hello, ${name}! You are ${age} years old.`;
// 多行字符串
const message = `
This is a multi-line
string using template literals.
`;
// 表达式计算
const total = `The total is ${10 + 20}.`;
解构赋值允许从数组或对象中提取值并赋值给变量。
// 数组解构
const numbers = [1, 2, 3];
const [a, b, c] = numbers; // a=1, b=2, c=3
// 对象解构
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
const { firstName, age } = person; // firstName='John', age=30
// 别名和默认值
const { firstName: name, city = 'Unknown' } = person;
扩展运算符(...
)可以展开数组或对象。
// 数组扩展
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
// 合并数组
const merged = [...arr1, ...arr2]; // [1, 2, 1, 2, 3, 4]
// 对象扩展
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
// 函数参数展开
const numbers = [1, 2, 3];
console.log(Math.max(...numbers)); // 3
ES6 引入了类的语法糖,基于原型实现面向对象编程。
// 类定义
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
// 继承
class Dog extends Animal {
constructor(name) {
super(name); // 调用父类构造函数
}
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Buddy');
dog.speak(); // "Buddy barks."
注意:
extends
关键字实现继承constructor
方法用于初始化对象super()
调用父类的构造函数或方法Promise 用于处理异步操作,解决回调地狱问题。
// Promise 基本用法
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const data = { name: 'John', age: 30 };
resolve(data); // 操作成功
// reject(new Error('Failed to fetch data')); // 操作失败
}, 1000);
});
// 使用 Promise
fetchData
.then(data => console.log(data))
.catch(error => console.error(error));
// Promise 链式调用
fetchData
.then(data => processData(data))
.then(result => displayResult(result))
.catch(error => handleError(error));
ES6 引入了官方的模块系统,替代了 CommonJS 和 AMD。
// 导出模块
// utils.js
export const PI = 3.14159;
export function calculateCircleArea(radius) {
return PI * radius * radius;
}
// 导入模块
// main.js
import { PI, calculateCircleArea } from './utils.js';
console.log(calculateCircleArea(5));
// 导入整个模块
import * as utils from './utils.js';
console.log(utils.PI);
// 默认导出
// logger.js
export default function log(message) {
console.log(`[LOG] ${message}`);
}
// 导入默认导出
import log from './logger.js';
log('This is a message');
函数参数可以设置默认值,当参数未传递时使用默认值。
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // "Hello, Guest!"
greet('Alice'); // "Hello, Alice!"
剩余参数允许将不确定数量的参数收集为一个数组。
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
ES6 引入了新的数据结构 Map
和 Set
,提供了更高效的数据存储和查找方式。
// Map 示例:键值对集合
const myMap = new Map();
myMap.set('name', 'John');
myMap.set(1, 'One');
console.log(myMap.get('name')); // "John"
console.log(myMap.size); // 2
// Set 示例:唯一值集合
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // 重复值会被忽略
console.log(mySet.has(1)); // true
console.log(mySet.size); // 2
特点:
Map
:键可以是任意类型,保持插入顺序,提供高效的查找Set
:值唯一,自动去重,提供高效的成员检测迭代器是一种接口,为各种不同的数据结构提供统一的访问机制。
// 数组迭代
const numbers = [1, 2, 3];
for (const num of numbers) {
console.log(num); // 1, 2, 3
}
// 字符串迭代
const str = 'hello';
for (const char of str) {
console.log(char); // 'h', 'e', 'l', 'l', 'o'
}
// 自定义迭代器
const myIterable = {
[Symbol.iterator]() {
let i = 0;
return {
next() {
return i < 3 ? { value: i++, done: false } : { done: true };
}
};
}
};
for (const value of myIterable) {
console.log(value); // 0, 1, 2
}
生成器是一种特殊的函数,可以暂停执行并在需要时恢复。
// 生成器函数
function* countNumbers() {
let i = 0;
while (true) {
yield i++;
}
}
const counter = countNumbers();
console.log(counter.next().value); // 0
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
// 生成器用于迭代
function* evenNumbers() {
let i = 0;
while (i < 10) {
yield i;
i += 2;
}
}
for (const num of evenNumbers()) {
console.log(num); // 0, 2, 4, 6, 8
}
关键点:
function*
定义生成器函数yield
关键字暂停函数执行并返回值ES6 的这些新特性极大地提升了 JavaScript 的表达能力和开发效率,使代码更加简洁、优雅和易于维护。本文介绍了 ES6 中最核心的特性,包括块级作用域、箭头函数、模板字符串、解构赋值、扩展运算符、类和继承、Promise、模块化等,以及补充的 Map/Set 数据结构、迭代器和生成器。