es6新特性

by Admin


Posted on 2026-02-12 08:00   Views: 11


ES6 新特性详解

1. 块级作用域

let 和 const

ES6 引入了 letconst 关键字,用于声明块级作用域的变量。

// let 声明的变量只在块级作用域内有效
function test() {
    if (true) {
        let x = 10;
        console.log(x); // 10
    }
    console.log(x); // 报错,x 未定义
}

// const 声明的是常量,不能重新赋值
const PI = 3.14159;
PI = 3; // 报错,不能修改常量

2. 箭头函数

箭头函数提供了更简洁的函数写法,并且没有自己的 this

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

// 箭头函数写法
const add = (a, b) => a + b;

// 多行箭头函数
const multiply = (a, b) => {
    const result = a * b;
    return result;
};

// 箭头函数中的 this
const obj = {
    name: 'John',
    sayHi: function() {
        setTimeout(() => {
            console.log(`Hi, ${this.name}`); // 这里的 this 指向 obj
        }, 1000);
    }
};

3. 模板字符串

模板字符串使用反引号 (`) 包围,可以在字符串中嵌入变量和表达式。

const name = 'John';
const age = 30;

// 传统字符串拼接
const message = 'My name is ' + name + ', and I am ' + age + ' years old.';

// 模板字符串
const message = `My name is ${name}, and I am ${age} years old.`;

// 多行模板字符串
const html = `
    

${name}

${age} years old


`;

4. 解构赋值

解构赋值允许从数组或对象中提取值,并赋给变量。

// 数组解构
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3

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

// 解构赋值的默认值
const [x, y = 5] = [1];
console.log(x, y); // 1 5

// 函数参数解构
function greet({ name, age }) {
    console.log(`Hello, ${name}. You are ${age} years old.`);
}

greet({ name: 'John', age: 30 });

5. 扩展运算符

扩展运算符 (...) 用于展开数组或对象。

// 展开数组
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]

// 展开对象
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }

// 函数参数展开
function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

6. 类

ES6 引入了类的概念,使面向对象编程更加直观。

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    greet() {
        console.log(`Hello, my name is ${this.name}.`);
    }
    
    static info() {
        console.log('This is a Person class.');
    }
}

// 继承
class Student extends Person {
    constructor(name, age, grade) {
        super(name, age);
        this.grade = grade;
    }
    
    study() {
        console.log(`${this.name} is studying.`);
    }
}

const student = new Student('John', 15, 9);
student.greet(); // Hello, my name is John.
student.study(); // John is studying.
Person.info(); // This is a Person class.

7. 模块化

ES6 引入了模块化系统,使用 importexport 关键字。

// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

export { add, subtract };

// app.js
import { add, subtract } from './math.js';

console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2

// 导出默认值
// utils.js
export default {
    PI: 3.14159,
    random: () => Math.random()
};

// app.js
import utils from './utils.js';
console.log(utils.PI); // 3.14159

8. Promise

Promise 用于处理异步操作,使异步代码更加清晰。

// 创建 Promise
const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        const success = true;
        if (success) {
            resolve('操作成功');
        } else {
            reject('操作失败');
        }
    }, 1000);
});

// 使用 Promise
promise
    .then(result => {
        console.log(result); // 操作成功
    })
    .catch(error => {
        console.log(error); // 操作失败
    });

// Promise 链式调用
fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('Error:', error);
    });

9. async/await

async/await 是基于 Promise 的语法糖,使异步代码看起来像同步代码。

// async 函数返回一个 Promise
async function getData() {
    try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    }
}

// 使用 async 函数
getData()
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('Error:', error);
    });

// 在 async 函数中使用
async function processData() {
    try {
        const data = await getData();
        console.log('Processing data:', data);
    } catch (error) {
        console.error('Error:', error);
    }
}

10. 其他新特性

10.1 增强的对象字面量

// 简写属性
const name = 'John';
const age = 30;
const person = {
    name, // 等同于 name: name
    age,  // 等同于 age: age
    greet() { // 简写方法
        console.log(`Hello, ${this.name}.`);
    }
};

// 计算属性名
const key = 'name';
const obj = {
    [key]: 'John',
    [`age_${2023}`]: 30
};

10.2 Set 和 Map

// Set 用于存储唯一值
const set = new Set();
set.add(1);
set.add(2);
set.add(1); // 重复值不会被添加
console.log(set.size); // 2
console.log(set.has(1)); // true

// Map 用于存储键值对
const map = new Map();
map.set('name', 'John');
map.set('age', 30);
console.log(map.get('name')); // John
console.log(map.size); // 2

10.3 新的数组方法

// Array.from()
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
const arr = Array.from(arrayLike);
console.log(arr); // ['a', 'b']

// Array.includes()
const arr = [1, 2, 3];
console.log(arr.includes(2)); // true
console.log(arr.includes(4)); // false

// Array.find() 和 Array.findIndex()
const arr = [1, 2, 3, 4, 5];
const found = arr.find(item => item > 3);
console.log(found); // 4
const index = arr.findIndex(item => item > 3);
console.log(index); // 3

总结

ES6 引入了许多新特性,使 JavaScript 代码更加简洁、可读性更高、功能更强大。这些新特性包括:

  • 块级作用域(let 和 const)
  • 箭头函数
  • 模板字符串
  • 解构赋值
  • 扩展运算符
  • 模块化
  • Promise
  • async/await
  • 增强的对象字面量
  • Set 和 Map
  • 新的数组方法

掌握这些 ES6 新特性,可以帮助你编写更现代、更高效的 JavaScript 代码。


搜索
分类
关于本文
本文发布于 2026-02-12,最后更新于 2026-02-12。