JavaScript ES6+ 新特性概览

/ 0

ECMAScript 6(ES6)及后续版本为 JavaScript 带来了许多强大的新特性。

let 和 const

块级作用域变量声明:

let x = 10;
const PI = 3.14159;

箭头函数

简洁的函数语法:

const add = (a, b) => a + b;
const greet = name => `Hello, ${name}!`;

模板字符串

const name = "World";
console.log(`Hello, ${name}!`);

解构赋值

// 数组解构
const [a, b] = [1, 2];

// 对象解构
const {name, age} = {name: "Alice", age: 25};

展开运算符

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];

const obj1 = {a: 1};
const obj2 = {...obj1, b: 2};

Promise

处理异步操作:

fetch('/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

async/await

更优雅的异步代码:

async function fetchData() {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

面向对象编程:

class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, I'm ${this.name}`);
  }
}

模块

// 导出
export const name = "Module";
export default function() {}

// 导入
import defaultExport, {name} from './module.js';

这些特性让 JavaScript 开发更加现代化和高效!