ES6 核心语法精讲


一、变量声明

javascript

复制代码
// let 块级作用域变量
let count = 0
count = 1  // ✅ 可重新赋值
if (true) {
    let count = 2  // ✅ 新的块级变量
}

// const 常量(引用不可变)
const PI = 3.14159
// PI = 3.14  // ❌ 报错

const user = { name: 'John' }
user.name = 'Jane'  // ✅ 可修改属性
// user = {}  // ❌ 不可重新赋值

二、箭头函数

javascript

复制代码
// 语法:(参数) => 返回值
const add = (a, b) => a + b

// 相当于:
const add = function(a, b) {
    return a + b
}

// this 绑定(无自己的this)
const person = {
    name: 'John',
    sayName: function() {
        setTimeout(() => {
            console.log(this.name)  // ✅ 正确:John
        }, 100)
    }
}

三、模板字符串

javascript

复制代码
const name = 'John'
const age = 25

// 插值
const msg = `姓名:${name},年龄:${age}`

// 多行
const html = `
    <div>
        <h1>${name}</h1>
    </div>
`

// 表达式
const result = `${1 + 2} = ${add(1, 2)}`

四、解构赋值

javascript

复制代码
// 数组解构
const [a, b, ...rest] = [1, 2, 3, 4]
// a=1, b=2, rest=[3,4]

// 对象解构
const { name, age } = { name: 'John', age: 25 }
const { name: userName } = { name: 'John' }
// userName='John'

// 函数参数解构
function print({ name, age }) {
    console.log(`${name}, ${age}`)
}

五、函数增强

javascript

复制代码
// 默认参数
function greet(name = 'Guest') {
    return `Hello, ${name}`
}

// 剩余参数
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b)
}
sum(1, 2, 3)  // 6

// 参数解构 + 默认值
function createUser({ name = 'Anon', age = 0 } = {}) {
    return { name, age }
}

六、扩展运算符

javascript

复制代码
// 数组展开
const arr1 = [1, 2]
const arr2 = [...arr1, 3, 4]  // [1,2,3,4]

// 对象展开(浅拷贝)
const obj1 = { a: 1, b: 2 }
const obj2 = { ...obj1, c: 3 }  // {a:1,b:2,c:3}

// 数组合并
const merged = [...arr1, ...arr2]

// 函数参数展开
Math.max(...[1, 2, 3])  // 相当于 Math.max(1,2,3)

七、对象简写

javascript

复制代码
const name = 'John'
const age = 25

// 属性简写
const user = { name, age }
// 相当于 { name: name, age: age }

// 方法简写
const obj = {
    sayHi() {  // 代替 sayHi: function() {}
        console.log('Hi')
    }
}

// 计算属性名
const key = 'status'
const obj2 = {
    [key]: 'active',
    ['get_' + key]() {
        return this[key]
    }
}

八、Class 类

javascript

复制代码
// 定义类
class Person {
    constructor(name, age) {
        this.name = name
        this.age = age
    }
    
    // 方法
    sayHi() {
        return `Hi, I'm ${this.name}`
    }
    
    // Getter/Setter
    get info() {
        return `${this.name}, ${this.age}`
    }
    
    // 静态方法
    static create(name) {
        return new Person(name, 0)
    }
}

// 继承
class Employee extends Person {
    constructor(name, age, title) {
        super(name, age)  // 调用父类构造函数
        this.title = title
    }
}

const john = new Person('John', 25)
john.sayHi()

九、模块化

javascript

复制代码
// module.js
export const PI = 3.14159
export function add(a, b) { return a + b }
export default class Calculator {}

// app.js
import Calculator, { PI, add } from './module.js'
import * as Module from './module.js'

// 动态导入
const module = await import('./module.js')

十、Promise 与 Async/Await

javascript

复制代码
// Promise 基础
fetch(url)
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error))

// Promise 组合
Promise.all([promise1, promise2])  // 全部成功
Promise.race([promise1, promise2]) // 最先完成

// Async/Await(同步写法)
async function getData() {
    try {
        const response = await fetch(url)
        const data = await response.json()
        return data
    } catch (error) {
        console.error(error)
    }
}

十一、迭代器与生成器

javascript

复制代码
// 迭代协议(可迭代对象)
const iterable = {
    [Symbol.iterator]() {
        let i = 0
        return {
            next() {
                return i < 3 
                    ? { value: i++, done: false }
                    : { done: true }
            }
        }
    }
}

// for...of 遍历
for (const item of iterable) {
    console.log(item)  // 0,1,2
}

// 生成器函数
function* counter() {
    yield 1
    yield 2
    yield 3
}

const gen = counter()
gen.next().value  // 1

十二、Set 和 Map

javascript

复制代码
// Set(唯一值集合)
const set = new Set([1, 2, 2, 3])  // {1,2,3}
set.add(4)
set.has(2)  // true
set.size  // 4

// Map(键值对集合)
const map = new Map()
map.set('name', 'John')
map.get('name')  // 'John'
map.has('name')  // true

// WeakMap(弱引用,防止内存泄漏)
const wm = new WeakMap()
wm.set(obj, 'value')  // 键必须是对象

十三、实用新方法

javascript

复制代码
// 字符串
'hello'.includes('ell')   // true
'hello'.startsWith('he')  // true
'hello'.endsWith('lo')    // true
'hi'.repeat(3)            // 'hihihi'

// 数组
[1, 2, 3].find(x => x > 1)      // 2
[1, 2, 3].findIndex(x => x > 1) // 1
[1, 2, 3].fill(0)               // [0,0,0]
Array.from('abc')               // ['a','b','c']

// 对象
Object.assign({}, {a:1}, {b:2}) // {a:1,b:2}
Object.entries({a:1,b:2})       // [['a',1],['b',2]]
Object.values({a:1,b:2})        // [1,2]

十四、常用模式示例

javascript

复制代码
// 1. 合并对象(覆盖顺序从右到左)
const config = {
    ...defaultConfig,
    ...userConfig,
    ...overrides
}

// 2. 条件对象属性
const user = {
    name: 'John',
    ...(isAdmin && { role: 'admin' })
}

// 3. 异步数据获取
async function loadData() {
    const [user, posts] = await Promise.all([
        fetchUser(),
        fetchPosts()
    ])
    return { user, posts }
}

// 4. 数据转换
const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' }
]

const userMap = new Map(
    users.map(user => [user.id, user])
)

// 5. 错误处理包装
const safeGet = async (url) => {
    try {
        const res = await fetch(url)
        return await res.json()
    } catch {
        return null
    }
}

核心要点总结

  1. let/const → 块级作用域变量

  2. 箭头函数 → 简写 + this绑定

  3. 解构 → 快速提取数据

  4. 模板字符串 → 字符串插值

  5. 扩展运算符 → 数组/对象操作

  6. Class → 面向对象语法糖

  7. 模块化 → 代码组织

  8. Promise/Async → 异步处理

  9. 新数据结构 → Set/Map

  10. 对象增强 → 简化对象操作

掌握这些核心语法,即可编写现代、简洁的 JavaScript 代码。

相关推荐
代码匠心21 小时前
AI 自动编程:一句话设计高颜值博客
前端·ai·ai编程·claude
_AaronWong1 天前
Electron 实现仿豆包划词取词功能:从 AI 生成到落地踩坑记
前端·javascript·vue.js
cxxcode1 天前
I/O 多路复用:从浏览器到 Linux 内核
前端
用户5433081441941 天前
AI 时代,前端逆向的门槛已经低到离谱 — 以 Upwork 为例
前端
JarvanMo1 天前
Flutter 版本的 material_ui 已经上架 pub.dev 啦!快来抢先体验吧。
前端
恋猫de小郭1 天前
AI 可以让 WIFI 实现监控室内人体位置和姿态,无需摄像头?
前端·人工智能·ai编程
哀木1 天前
给自己整一个 claude code,解锁编程新姿势
前端
程序员鱼皮1 天前
GitHub 关注突破 2w,我总结了 10 个涨星涨粉技巧!
前端·后端·github
UrbanJazzerati1 天前
Vue3 父子组件通信完全指南
前端·面试
是一碗螺丝粉1 天前
5分钟上手LangChain.js:用DeepSeek给你的App加上AI能力
前端·人工智能·langchain