ES6详解
一、变量声明
-
let
与const
-
块级作用域:替代
var
的函数作用域-
const
声明常量(不可重新赋值,但对象属性可修改)
-
if (true) {let x = 10const PI = 3.14 } console.log(x) // 报错
-
二、箭头函数
-
简写语法与
this
绑定// 传统函数 function add(a, b) { return a + b }// 箭头函数 const add = (a, b) => a + b// this 继承上下文 document.addEventListener('click', () => {console.log(this) // 指向外层 this })
三、模板字符串
-
多行文本与变量插值
const name = "Alice" console.log(`Hello ${name}, Today is ${new Date().toDateString()}`)
四、解构赋值
-
数组与对象解构
// 数组 const [a, b] = [1, 2]// 对象 const { name, age } = user // 重命名 const { name: userName } = user
五、函数增强
-
默认参数与剩余参数
function greet(name = 'Guest', ...args) {console.log(`Hello ${name}`) }
六、Class 类
-
面向对象语法糖
class Person {constructor(name) {this.name = name}sayHi() {console.log(`Hi, I'm ${this.name}`)}static create() {return new Person('Anonymous')} }
七、模块化
-
import/export
语法// math.js export const PI = 3.14 export function sum(a, b) { return a + b }// app.js import { PI, sum } from './math.js'
八、Promise 与异步
-
异步编程方案
fetch('/data').then(response => response.json()).then(data => console.log(data)).catch(error => console.error(error))
九、其他重要特性
-
展开运算符
const arr = [1, ...[2,3], 4]
-
Symbol 类型
const id = Symbol('unique identifier')
-
Map/Set 集合
const map = new Map() map.set('key', 'value')
十、兼容与工具
-
Babel 转译:将 ES6+ 代码转为 ES5
-
Polyfill:补充浏览器缺失 API(如 core-js)
ES6 极大提升了 JavaScript 的表现力与工程化能力,是现代前端开发的基石。建议通过实际项目练习掌握这些特性。