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 代码。

相关推荐
GISer_Jing2 小时前
一次编码,七端运行:Taro多端统一架构深度解析与电商实战
前端·aigc·taro
michael_ouyang2 小时前
IM 消息收发流程方案选型
前端·websocket·网络协议·typescript·electron
Y淑滢潇潇2 小时前
WEB 作业 三个练习题
前端·javascript·css3
静小谢2 小时前
前端mock假数据工具JSON Server使用笔记
前端·笔记·json
敲上瘾3 小时前
用Coze打造你的专属AI应用:从智能体到Web部署指南
前端·人工智能·python·阿里云·aigc
EndingCoder3 小时前
性能优化:类型系统的最佳实践
linux·前端·javascript·ubuntu·性能优化·typescript
毕设源码-朱学姐3 小时前
【开题答辩全过程】以 基于web的生鲜农产品信息管理系统为例,包含答辩的问题和答案
前端
Hello.Reader3 小时前
Flink 2.0 从 flink-conf.yaml 到 config.yaml 的正确打开方式(含迁移与最佳实践)
java·前端·flink
晚霞的不甘3 小时前
Flutter for OpenHarmony:注入灵魂:购物车的数据驱动与状态管理实战
android·前端·javascript·flutter·前端框架