ES6 核心语法手册

发布于:2025-06-10 ⋅ 阅读:(13) ⋅ 点赞:(0)

ES6 核心语法手册


一、变量声明

关键字 作用域 是否可重定义 是否可修改 特性
let 块级作用域 替代 var 的首选
const 块级作用域 声明常量(对象属性可修改)
// 示例
let name = "Alice";
name = "Bob"; // ✅

const PI = 3.14;
// PI = 3.15; ❌ 报错

const user = { name: "John" };
user.name = "Mike"; // ✅ 对象属性可修改

二、箭头函数

// 传统函数
function sum(a, b) {
  return a + b;
}

// 箭头函数
const sum = (a, b) => a + b;

// 特性:
// 1. 无自己的 this(继承外层上下文)
// 2. 不能用作构造函数
// 3. 无 arguments 对象

// 示例:this 绑定
const obj = {
  value: 10,
  getValue: function() {
    setTimeout(() => {
      console.log(this.value); // ✅ 输出 10(箭头函数继承 this)
    }, 100);
  }
};

三、模板字符串

const name = "Alice";
const age = 28;

// 多行字符串
const bio = `姓名:${name}
年龄:${age}
职业:工程师`;

// 表达式计算
console.log(`明年年龄:${age + 1}`); // 输出:明年年龄:29

// 标签模板(高级用法)
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => 
    `${result}${str}<mark>${values[i] || ''}</mark>`, '');
}
highlight`Hello ${name}`; // <mark>Hello</mark><mark>Alice</mark>

四、解构赋值

// 数组解构
const [first, second, , fourth] = [10, 20, 30, 40];
console.log(first); // 10

// 对象解构
const { name, age: userAge } = { name: "Bob", age: 30 };
console.log(userAge); // 30

// 函数参数解构
function getUser({ id, name = "Unknown" }) {
  console.log(`ID: ${id}, Name: ${name}`);
}
getUser({ id: 1 }); // ID: 1, Name: Unknown

五、扩展运算符与剩余参数

// 数组扩展
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]

// 对象扩展
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }

// 剩余参数
function sum(...numbers) {
  return numbers.reduce((acc, cur) => acc + cur, 0);
}
sum(1, 2, 3); // 6

六、类与继承

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(`${this.name} makes a noise`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
  
  speak() {
    super.speak();
    console.log("Woof!");
  }
}

const rex = new Dog("Rex", "Labrador");
rex.speak();

七、模块化

// 📁 math.js
export const PI = 3.14159;
export function square(x) { return x * x; }
export default function cube(x) { return x * x * x; }

// 📁 app.js
import { PI, square } from './math.js';
import cube from './math.js'; // 导入默认导出

console.log(square(PI)); // 9.8690227281

八、Promise 与异步

// 创建 Promise
const fetchData = () => new Promise((resolve, reject) => {
  setTimeout(() => Math.random() > 0.5 ? 
    resolve("成功!") : reject("失败!"), 1000);
});

// 使用 Promise
fetchData()
  .then(data => console.log(data))
  .catch(error => console.error(error));

// Async/Await
async function getData() {
  try {
    const result = await fetchData();
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

九、新增数据结构

类型 特性 常用方法
Set 值唯一的集合 add(), delete(), has()
Map 键值对集合(键可以是任意类型) set(), get(), has()
WeakSet 弱引用集合(仅存储对象) add(), delete(), has()
WeakMap 弱引用键值对(键必须是对象) set(), get(), has()
// Set 示例
const uniqueNumbers = new Set([1, 2, 2, 3]);
console.log([...uniqueNumbers]); // [1, 2, 3]

// Map 示例
const userMap = new Map();
userMap.set(1, { name: "Alice" });
console.log(userMap.get(1)); // { name: "Alice" }

十、其他重要特性

  1. Symbol - 创建唯一标识符

    const id = Symbol("uniqueID");
    console.log(id === Symbol("uniqueID")); // false
    
  2. 迭代器与生成器

    function* idGenerator() {
      let id = 1;
      while (true) yield id++;
    }
    const gen = idGenerator();
    console.log(gen.next().value); // 1
    
  3. Proxy 与 Reflect(元编程)

    const handler = {
      get(target, prop) {
        return prop in target ? target[prop] : 37;
      }
    };
    const p = new Proxy({}, handler);
    console.log(p.a); // 37
    

ES6 兼容性解决方案

  1. 使用 Babel 进行代码转换
  2. 配合 Webpack/Rollup 打包
  3. 核心特性现代浏览器已原生支持(可查 Can I Use)