ES6+特性
ES6(ECMAScript 2015)是JavaScript的一个重要版本,引入了许多现代化的语言特性,极大地提升了开发效率和代码可读性。ES6+指的是ES6及其后续版本(ES2016、ES2017等)。
let和const
let
let用于声明块级作用域的变量:
javascript
if (true) {
let x = 10;
console.log(x); // 10
}
console.log(x); // ReferenceError: x is not defined
const
const用于声明常量,一旦赋值就不能改变:
javascript
const PI = 3.14159;
PI = 3; // TypeError: Assignment to constant variable.
// 但对象和数组的内容可以修改
const person = { name: "John" };
person.name = "Jane"; // 允许
person = { name: "Bob" }; // TypeError
箭头函数
箭头函数提供了更简洁的函数语法,并且没有自己的this:
javascript
// 传统函数
function add(a, b) {
return a + b;
}
// 箭头函数
const add = (a, b) => a + b;
// 带多条语句的箭头函数
const greet = (name) => {
console.log(`Hello, ${name}!`);
return `Hello, ${name}!`;
};
模板字符串
模板字符串使用反引号(`),可以嵌入表达式:
javascript
const name = "World";
const message = `Hello, ${name}!`;
console.log(message); // Hello, World!
// 多行模板字符串
const html = `
<div>
<h1>标题</h1>
<p>内容</p>
</div>
`;
解构赋值
解构赋值允许从数组或对象中提取值并赋给变量:
数组解构
javascript
const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]
对象解构
javascript
const person = { name: "John", age: 30 };
const { name, age } = person;
console.log(name); // John
console.log(age); // 30
// 重命名变量
const { name: fullName } = person;
console.log(fullName); // John
展开运算符
展开运算符(...)用于将数组或对象的元素展开:
数组展开
javascript
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
// 复制数组
const arr3 = [...arr1];
对象展开
javascript
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
// 合并对象
const obj3 = { ...obj1, ...obj2 };
类
ES6引入了类语法,使面向对象编程更加直观:
javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
static create(name, age) {
return new Person(name, age);
}
}
const person = new Person("John", 30);
person.greet(); // Hello, my name is John.
const person2 = Person.create("Jane", 25);
模块化
ES6支持原生模块化,使用import和export:
导出
javascript
// 命名导出
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// 默认导出
export default class Person {
// ...
}
导入
javascript
// 导入命名导出
import { add, subtract } from "./math.js";
// 导入默认导出
import Person from "./person.js";
// 导入所有命名导出
import * as math from "./math.js";
Promise
Promise用于处理异步操作:
javascript
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("数据获取成功");
// 或 reject("数据获取失败");
}, 1000);
});
};
fetchData()
.then(data => console.log(data))
.catch(error => console.log(error))
.finally(() => console.log("操作完成"));
其他ES6+特性
- 默认参数:
function greet(name = "World") { ... } - 剩余参数:
function sum(...numbers) { ... } - Set和Map:新的数据结构
- for…of:迭代数组和可迭代对象
- Symbol:唯一标识符
- Generator:生成器函数
学习资源
继续学习:面向对象编程
最后更新:2026-02-08