代码教程
最全的ES6新特性详解与应用实例
一、块级作用域变量(let和const)
(一)特性解析
-
let关键字
- 块级作用域
- 不存在变量提升
- 暂时性死区
- 不允许重复声明
-
const关键字
- 声明常量,一旦声明必须赋值
- 常量值不能通过重新赋值来改变
- 块级作用域
- 对于引用类型,可以修改其内部属性
(二)应用实例
// let示例
function letExample() {
if (true) {
let x = 10;
}
console.log(x); // 报错:x is not defined
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 输出0, 1, 2
}
}
// const示例
const PI = 3.14;
// PI = 3.1415; // 报错:Assignment to constant variable
const person = { name: 'John' };
person.name = 'Mike'; // 合法:修改对象属性
// person = {}; // 报错:Assignment to constant variable
二、箭头函数(Arrow Functions)
(一)特性解析
- 简洁语法
// 传统函数
function add(a, b) { return a + b; }
// 箭头函数
const add = (a, b) => a + b;
- 不绑定this
- 箭头函数不绑定自己的this,它继承自外层函数
- 不能使用arguments对象
- 不能使用yield关键字
(二)应用实例
// 传统函数的this问题
function Person() {
this.age = 0;
setInterval(function growUp() {
this.age++; // 这里的this指向全局对象或undefined(严格模式)
}, 1000);
}
// 使用箭头函数解决this问题
function Person() {
this.age = 0;
setInterval(() => {
this.age++; // 这里的this指向Person实例
}, 1000);
}
// 数组方法中的箭头函数
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8]
三、模板字符串(Template Literals)
(一)特性解析
- 多行字符串
const message = `这是一个
多行
字符串`;
- 插值表达式
const name = 'John';
const greeting = `Hello, ${name}!`;
- 标签模板
function highlight(strings, ...values) {
let result = '';
strings.forEach((string, i) => {
result += string;
if (i < values.length) {
result += `<strong>${values[i]}</strong>`;
}
});
return result;
}
const name = 'John';
const age = 30;
const output = highlight`${name} is ${age} years old.`;
// 输出: John is <strong>30</strong> years old.
四、解构赋值(Destructuring Assignment)
(一)数组解构
// 基本用法
const [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
// 剩余元素
const [first, ...rest] = [1, 2, 3, 4];
console.log(rest); // [2, 3, 4]
// 默认值
const [x = 10, y = 20] = [5];
console.log(x); // 5
console.log(y); // 20
(二)对象解构
// 基本用法
const { name, age } = { name: 'John', age: 30 };
console.log(name); // John
console.log(age); // 30
// 重命名
const { name: userName, age: userAge } = { name: 'John', age: 30 };
console.log(userName); // John
// 嵌套对象
const person = {
name: 'John',
address: {
city: 'New York',
country: 'USA'
}
};
const { address: { city } } = person;
console.log(city); // New York
五、默认参数(Default Parameters)
(一)特性解析
// 基本用法
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
console.log(greet()); // Hello, Guest!
console.log(greet('John')); // Hello, John!
// 表达式作为默认值
function calculateTotal(price, tax = price * 0.1) {
return price + tax;
}
console.log(calculateTotal(100)); // 110
六、扩展运算符(Spread Operator)
(一)数组扩展
// 数组拷贝
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
console.log(arr2); // [1, 2, 3]
// 数组合并
const arr3 = [4, 5];
const merged = [...arr1, ...arr3];
console.log(merged); // [1, 2, 3, 4, 5]
// 函数参数展开
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
(二)对象扩展
// 对象拷贝
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1 };
console.log(obj2); // { a: 1, b: 2 }
// 对象合并
const obj3 = { c: 3 };
const mergedObj = { ...obj1, ...obj3 };
console.log(mergedObj); // { a: 1, b: 2, c: 3 }
// 覆盖属性
const obj4 = { a: 10, d: 4 };
const mergedWithOverride = { ...obj1, ...obj4 };
console.log(mergedWithOverride); // { a: 10, b: 2, d: 4 }
七、类(Class)与继承
(一)类的定义
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I'm ${this.age} years old.`;
}
static info() {
return 'This is a Person class.';
}
}
const person = new Person('John', 30);
console.log(person.greet()); // Hello, my name is John and I'm 30 years old.
console.log(Person.info()); // This is a Person class.
(二)继承
class Employee extends Person {
constructor(name, age, position) {
super(name, age);
this.position = position;
}
introduce() {
return `${super.greet()} I'm a ${this.position}.`;
}
}
const employee = new Employee('Mike', 25, 'Developer');
console.log(employee.introduce()); // Hello, my name is Mike and I'm 25 years old. I'm a Developer.
八、Promise对象
(一)特性解析
-
三种状态
- pending:初始状态
- fulfilled:操作成功完成
- rejected:操作失败
-
链式调用
- then()方法返回一个新的Promise
- catch()方法处理错误
- finally()方法无论结果如何都会执行
(二)应用实例
// Promise基本用法
function fetchData() {
return 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:', data);
return data.age;
})
.then(age => {
console.log('Age:', age);
})
.catch(error => {
console.error('Error:', error.message);
})
.finally(() => {
console.log('Finally');
});
// 并行执行多个Promise
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
Promise.all([promise1, promise2, promise3])
.then(values => {
console.log('All results:', values); // [1, 2, 3]
});
九、模块化(Module)
(一)导出(Export)
// utils.js
export const PI = 3.14;
export function calculateCircleArea(radius) {
return PI * radius * radius;
}
export class Calculator {
add(a, b) {
return a + b;
}
}
// 或统一导出
const name = 'Utils';
const version = '1.0.0';
export { name, version };
(二)导入(Import)
// main.js
import { PI, calculateCircleArea, Calculator } from './utils.js';
console.log(PI); // 3.14
console.log(calculateCircleArea(5)); // 78.5
const calculator = new Calculator();
console.log(calculator.add(2, 3)); // 5
// 导入全部
import * as utils from './utils.js';
console.log(utils.PI); // 3.14
// 默认导出
// math.js
export default function add(a, b) {
return a + b;
}
// 使用默认导出
import add from './math.js';
console.log(add(1, 2)); // 3
十、其他重要特性
(一)Promise.allSettled()
const promises = [
Promise.resolve(1),
Promise.reject(new Error('Error')),
Promise.resolve(3)
];
Promise.allSettled(promises)
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Fulfilled:', result.value);
} else {
console.log('Rejected:', result.reason);
}
});
});
(二)String.prototype.matchAll()
const regex = /\b(apple|banana|cherry)\b/g;
const text = 'I like apples and bananas.';
const matches = text.matchAll(regex);
for (const match of matches) {
console.log(match[0]); // 输出 "apple" 和 "banana"
}
(三)可选链操作符(?.)
const person = {
name: 'John',
address: {
city: 'New York'
}
};
// 传统写法
const zipCode = person.address && person.address.zipCode;
// 可选链写法
const zipCode = person.address?.zipCode;
(四)空值合并操作符(??)
const value = null;
const defaultValue = 'Default';
// 使用空值合并操作符
const result = value ?? defaultValue; // 'Default'
// 与逻辑或操作符对比
const resultOr = value || defaultValue; // 'Default'
const value2 = 0;
const result2 = value2 ?? 'Default'; // 0
const result2Or = value2 || 'Default'; // 'Default'
十一、总结
ES6引入了众多重要特性,显著提升了JavaScript的语言表达能力和开发效率。主要包括:
- 变量声明:let和const提供块级作用域
- 函数特性:箭头函数简化语法并解决this指向问题
- 数据结构:解构赋值和扩展运算符增强数据处理能力
- 面向对象:类和继承提供更清晰的对象模型
- 异步编程:Promise为异步操作提供标准化解决方案
- 模块化:ES6模块系统提供官方的模块解决方案
- 其他特性:模板字符串、默认参数、可选链等实用功能
这些特性已成为现代JavaScript开发的基础,广泛应用于各类项目中。掌握ES6特性是成为一名优秀前端开发者的必备技能。
代码获取方式
关注我获取更多内容