ES6特性介绍
- 变量声明:let 与 const
let:块级作用域变量,替代 var 避免变量提升和污染全局。
if (true) {
let x = 10;
console.log(x); // 10
}
console.log(x); // ReferenceError
const:声明常量,不可重新赋值(但对象属性可修改)。
const PI = 3.14;
PI = 3; // TypeError
const obj = { a: 1 };
obj.a = 2; // 允许
- 箭头函数(Arrow Functions)
更简洁的语法,自动绑定当前 this(解决传统函数 this 指向问题)。
// 传统函数
function add(a, b) { return a + b; }
// 箭头函数
const add = (a, b) => a + b;
注意:无自己的 arguments 对象,不能用作构造函数。
- 模板字符串(Template Literals)
支持多行字符串和变量嵌入(${expression})。
const name = "Alice";
const message = `Hello, ${name}!
How are you today?`;
- 解构赋值(Destructuring)
从数组或对象中提取值到变量。
// 数组解构
const [x, y] = [1, 2]; // x=1, y=2
// 对象解构
const { name, age } = { name: "Bob", age: 30 };
- 默认参数(Default Parameters)
函数参数支持默认值。
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
- 扩展运算符(Spread Operator)
展开数组或对象。
// 合并数组
const arr1 = [1, 2];
const arr2 = [...arr1, 3]; // [1, 2, 3]
// 合并对象
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }
- 剩余参数(Rest Parameters)
将不定数量的参数表示为数组。
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
sum(1, 2, 3); // 6
- 类(Classes)
语法糖,基于原型的面向对象编程更清晰。
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}!`);
}
}
const alice = new Person("Alice");
alice.greet();
- 模块化(Modules)
使用 import 和 export 管理代码模块。
// math.js
export const add = (a, b) => a + b;
// app.js
import { add } from './math.js';
console.log(add(2, 3)); // 5
- Promise 和异步处理
更优雅地处理异步操作,避免回调地狱。
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded"), 1000);
});
};
fetchData().then(data => console.log(data));
- 新增数据结构
Map 和 Set:
const map = new Map();
map.set("key", "value");
const set = new Set([1, 2, 2, 3]); // [1, 2, 3]
Symbol:唯一标识符,避免属性名冲突。
const id = Symbol("id");
ES6 的意义
代码更简洁、易读。
更好的异步处理和模块化支持。
为现代框架(React、Vue等)奠定基础。
2225

被折叠的 条评论
为什么被折叠?



