ES6 核心特性及优化的难点
1. 变量声明:let/const(解决 var 的痛点)
var 的问题:
// ❌ var 的问题
for(var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 输出: 3, 3, 3
var name = 'Tom';
var name = 'Jerry'; // 重复声明不报错
console.log(age); // undefined(变量提升)
var age = 18;
let/const 优化:
// ✅ let 块级作用域
for(let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 输出: 0, 1, 2
// ✅ const 常量声明
const PI = 3.14;
// PI = 3.1415; // 报错
// ✅ 暂时性死区
console.log(age); // ReferenceError
let age = 18;
2. 箭头函数(解决 this 指向问题)
传统函数的问题:
// ❌ this 指向混乱
const obj = {
name: 'Tom',
greet: function() {
setTimeout(function() {
console.log('Hello, ' + this.name); // this 指向 window
}, 100);
}
};
const calculator = {
numbers: [1, 2, 3],
sum: function() {
// 需要保存 this 引用
const that = this;
return this.numbers.map(function(num) {
return num + that.prefix; // 繁琐
});
}
};
箭头函数优化:
// ✅ 箭头函数没有自己的 this
const obj = {
name: 'Tom',
greet: function() {
setTimeout(() => {
console.log('Hello, ' + this.name); // this 指向 obj
}, 100);
}
};
const calculator = {
numbers: [1, 2, 3],
prefix: 10,
sum: function() {
return this.numbers.map(num => num + this.prefix); // 简洁
}
};
// 箭头函数的其他优势
const add = (a, b) => a + b; // 隐式返回
const log = msg => console.log(msg); // 单参数可不加括号
3. Class 语法(简化原型继承)
传统构造函数的痛点:
// ❌ 繁琐且容易出错
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes sound');
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log('Woof!');
};
Class 语法优化:
// ✅ 清晰简洁
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes sound`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 自动处理父类调用
this.breed = breed;
}
bark() {
console.log('Woof!');
}
static create(name) { // 静态方法
return new Dog(name, 'Mixed');
}
}
4. 模块化(解决代码组织问题)
传统方式的问题:
- 全局命名空间污染
- 依赖管理混乱
- 代码复用困难
ES6 模块化:
// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default class Calculator { /* ... */ }
// 导入方
import Calculator, { PI, add as sum } from './math.js';
import * as MathUtils from './math.js';
5. 解构赋值(简化数据提取)
传统方式:
// ❌ 繁琐
const user = { name: 'Tom', age: 18, address: { city: 'Beijing' } };
const name = user.name;
const age = user.age;
const city = user.address.city;
const arr = [1, 2, 3];
const first = arr[0];
const second = arr[1];
解构赋值优化:
// ✅ 简洁
const user = { name: 'Tom', age: 18, address: { city: 'Beijing' } };
const { name, age, address: { city } } = user;
const arr = [1, 2, 3];
const [first, second, third] = arr;
const [head, ...tail] = arr; // rest 操作符
// 默认值和重命名
const { name: username, role = 'user' } = user;
6. 扩展运算符和 Rest 参数
传统问题:数组合并、数组拷贝、函数参数处理繁琐
// ✅ 数组操作
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
const copy = [...arr1];
// ✅ 对象操作
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, ...obj1 }; // 合并
// ✅ Rest 参数(解决 arguments 问题)
function sum(...numbers) { // 真正的数组
return numbers.reduce((a, b) => a + b, 0);
}
7. Promise(解决回调地狱)
回调地狱:
// ❌ 回调地狱
getUser(function(user) {
getOrders(user.id, function(orders) {
getOrderDetails(orders[0].id, function(details) {
getPayment(details.id, function(payment) {
// 嵌套层次过深
});
});
});
});
Promise 优化:
// ✅ 链式调用
getUser()
.then(user => getOrders(user.id))
.then(orders => getOrderDetails(orders[0].id))
.then(details => getPayment(details.id))
.then(payment => console.log(payment))
.catch(error => console.error(error));
// Promise.all 并行处理
Promise.all([getUser(), getOrders(), getProducts()])
.then(([user, orders, products]) => { /* 全部完成 */ });
8. 模板字符串(解决字符串拼接)
// ❌ 繁琐的字符串拼接
const message = 'Hello, ' + name + '! You have ' + count + ' messages.';
// ✅ 模板字符串
const message = `Hello, ${name}! You have ${count} messages.`;
// 多行字符串
const html = `
<div class="card">
<h3>${title}</h3>
<p>${content}</p>
</div>
`;
9. Symbol(解决属性名冲突)
// 创建唯一标识符
const id1 = Symbol('id');
const id2 = Symbol('id');
console.log(id1 === id2); // false
const user = {
[Symbol('secret')]: 'hidden',
name: 'Tom'
};
// 防止属性被意外覆盖
const ITERATOR = Symbol('iterator');
class Collection {
[ITERATOR]() { /* 自定义迭代逻辑 */ }
}
10. Map/Set(增强的数据结构)
// Map:解决对象键只能是字符串的问题
const map = new Map();
const keyObj = {};
map.set(keyObj, 'value');
map.set(1, 'number');
map.set('name', 'Tom');
// Set:自动去重
const set = new Set([1, 2, 2, 3, 3, 4]);
console.log([...set]); // [1, 2, 3, 4]
// WeakMap/WeakSet:弱引用,避免内存泄漏
const wm = new WeakMap();
let element = {};
wm.set(element, 'data');
element = null; // 对象可被垃圾回收
总结对照表
| 痛点 | ES5 及之前 | ES6 解决方案 |
|---|---|---|
| 变量提升/全局污染 | var | let/const |
| this 绑定混乱 | 需要保存引用或 bind | 箭头函数 |
| 继承复杂 | 手动原型操作 | class/extend |
| 代码组织困难 | IIFE/AMD/CommonJS | import/export |
| 数据提取繁琐 | 逐一遍历 | 解构赋值 |
| 回调地域 | 多层嵌套 | Promise/async-await |
| 字符串拼接 | + 号连接 | 模板字符串 |
| 属性冲突 | 手动检查 | Symbol |
这些特性极大地提升了代码的可读性、可维护性和开发效率。

448

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



