ES6(ECMAScript 2015)基本语法全解析

ES6(ECMAScript 2015)是 JavaScript 语言的重大版本更新,引入了众多革命性的语法特性,极大提升了代码的可读性、可维护性和开发效率。本文将详细介绍 ES6 的核心语法特性。

一、let 和 const 声明

1. let 声明

let用于声明块级作用域变量,解决了var的变量提升和作用域问题:

javascript

运行

复制代码
// 块级作用域
{
  let a = 10;
  var b = 1;
}
console.log(a); // ReferenceError: a is not defined
console.log(b); // 1

// 不存在变量提升
console.log(c); // ReferenceError: Cannot access 'c' before initialization
let c = 3;

// 不可重复声明
let d = 1;
let d = 2; // SyntaxError: Identifier 'd' has already been declared

2. const 声明

const用于声明常量,具有块级作用域且声明后不可重新赋值:

javascript

运行

复制代码
const PI = 3.14159;
PI = 3; // TypeError: Assignment to constant variable

// 但对象/数组的属性可修改
const obj = { name: "ES6" };
obj.name = "ECMAScript 2015"; // 允许

// 必须立即初始化
const e; // SyntaxError: Missing initializer in const declaration

二、解构赋值

1. 对象解构

javascript

运行

复制代码
const user = { name: "张三", age: 20 };

// 基本解构
const { name, age } = user;
console.log(name); // 张三
console.log(age); // 20

// 重命名
const { name: userName, age: userAge } = user;

// 默认值
const { gender = "男" } = user;

// 嵌套解构
const person = {
  info: {
    id: 1,
    address: { city: "北京" }
  }
};
const { info: { address: { city } } } = person;

2. 数组解构

javascript

运行

复制代码
const arr = [1, 2, 3];

// 基本解构
const [a, b, c] = arr;

// 跳过元素
const [x, , z] = arr;

// 剩余参数
const [first, ...rest] = arr;

// 默认值
const [m, n = 0] = [1];

三、模板字符串

使用反引号(`)包裹,支持变量插值和多行字符串:

javascript

运行

复制代码
const name = "ES6";
const version = 2015;

// 变量插值
const str = `${name} 发布于 ${version} 年`;

// 多行字符串
const html = `
  <div>
    <p>Hello ${name}</p>
  </div>
`;

// 表达式计算
const a = 10, b = 20;
const result = `${a} + ${b} = ${a + b}`;

四、箭头函数

1. 基本语法

javascript

运行

复制代码
// 传统函数
const add = function(a, b) {
  return a + b;
};

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

// 单参数可省略括号
const double = num => num * 2;

// 多行函数体需用大括号和return
const sum = (a, b) => {
  const total = a + b;
  return total;
};

2. 特性

  • 没有自己的this,继承自外层作用域
  • 不能作为构造函数,不能使用new
  • 没有arguments对象
  • 不能使用yield关键字

五、函数参数

1. 默认参数

javascript

运行

复制代码
function greet(name = "Guest") {
  console.log(`Hello ${name}`);
}
greet(); // Hello Guest

2. 剩余参数

javascript

运行

复制代码
function sum(...args) {
  return args.reduce((total, num) => total + num, 0);
}
sum(1, 2, 3); // 6

3. 扩展运算符

javascript

运行

复制代码
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1,2,3,4,5]

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

六、对象扩展

1. 属性简写

javascript

运行

复制代码
const name = "ES6";
const version = 2015;

// 属性名与变量名相同时可简写
const obj = { name, version };

2. 方法简写

javascript

运行

复制代码
const obj = {
  // 传统写法
  add: function(a, b) {
    return a + b;
  },
  // 简写
  multiply(a, b) {
    return a * b;
  },
  // 箭头函数(不推荐,this指向问题)
  double: num => num * 2
};

3. 计算属性名

javascript

运行

复制代码
const key = "name";
const obj = {
  [key]: "ES6",
  [`${key}_length`]: 3
};

七、类(Class)

1. 类的定义

javascript

运行

复制代码
class Person {
  // 构造函数
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // 实例方法
  sayHello() {
    console.log(`Hello, I'm ${this.name}`);
  }

  // 静态方法
  static create(name, age) {
    return new Person(name, age);
  }
}

// 实例化
const person = new Person("张三", 20);
person.sayHello();

// 静态方法调用
const person2 = Person.create("李四", 25);

2. 继承

javascript

运行

复制代码
class Student extends Person {
  constructor(name, age, grade) {
    super(name, age); // 调用父类构造函数
    this.grade = grade;
  }

  study() {
    console.log(`${this.name} is studying`);
  }
}

八、模块化(Module)

1. 导出(export)

javascript

运行

复制代码
// 导出变量
export const name = "ES6";
export const version = 2015;

// 导出函数
export function add(a, b) {
  return a + b;
}

// 导出类
export class Person {}

// 默认导出
export default function() {
  console.log("default export");
}

// 批量导出
const PI = 3.14;
const double = num => num * 2;
export { PI, double };

2. 导入(import)

javascript

运行

复制代码
// 导入指定成员
import { name, add } from './module.js';

// 导入并重命名
import { name as moduleName } from './module.js';

// 导入默认导出
import defaultFunc from './module.js';

// 导入全部
import * as module from './module.js';

// 混合导入
import defaultFunc, { name } from './module.js';

九、Promise

用于处理异步操作:

javascript

运行

复制代码
const promise = new Promise((resolve, reject) => {
  // 异步操作
  setTimeout(() => {
    const success = true;
    if (success) {
      resolve("操作成功");
    } else {
      reject("操作失败");
    }
  }, 1000);
});

// 调用
promise
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  })
  .finally(() => {
    console.log("操作完成");
  });

十、迭代器和生成器

1. 生成器函数

javascript

运行

复制代码
function* generator() {
  yield 1;
  yield 2;
  yield 3;
  return 4;
}

const gen = generator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: 4, done: true }

十一、Set 和 Map 数据结构

1. Set

javascript

运行

复制代码
const set = new Set([1, 2, 3, 3]);
console.log(set); // Set {1, 2, 3}

set.add(4);
set.delete(2);
console.log(set.has(3)); // true
console.log(set.size); // 3
set.clear();

2. Map

javascript

运行

复制代码
const map = new Map();
map.set("name", "ES6");
map.set("version", 2015);

console.log(map.get("name")); // ES6
console.log(map.has("version")); // true
console.log(map.size); // 2
map.delete("version");
map.clear();

十二、其他特性

1. Array 扩展方法

javascript

运行

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

// Array.of
const arr = Array.of(1, 2, 3); // [1, 2, 3]

// find和findIndex
const result = [1, 2, 3].find(item => item > 2); // 3
const index = [1, 2, 3].findIndex(item => item > 2); // 2

// includes
console.log([1, 2, 3].includes(2)); // true

2. String 扩展方法

javascript

运行

复制代码
// startsWith/endsWith/includes
const str = "hello es6";
console.log(str.startsWith("hello")); // true
console.log(str.endsWith("es6")); // true
console.log(str.includes("es")); // true

// repeat
console.log("a".repeat(3)); // "aaa"

ES6 的语法特性极大丰富了 JavaScript 的表达能力,是现代前端开发的基础。掌握这些语法,能显著提升代码质量和开发效率。

相关推荐
ywf121528 分钟前
前端的dist包放到后端springboot项目下一起打包
前端·spring boot·后端
恋猫de小郭36 分钟前
2026,Android Compose 终于支持 Hot Reload 了,但是收费
android·前端·flutter
hpoenixf7 小时前
2026 年前端面试问什么
前端·面试
还是大剑师兰特7 小时前
Vue3 中的 defineExpose 完全指南
前端·javascript·vue.js
泯泷7 小时前
阶段一:从 0 看懂 JSVMP 架构,先在脑子里搭出一台最小 JSVM
前端·javascript·架构
mengchanmian8 小时前
前端node常用配置
前端
华洛8 小时前
利好打工人,openclaw不是企业提效工具,而是个人助理
前端·javascript·产品经理
xkxnq8 小时前
第六阶段:Vue生态高级整合与优化(第93天)Element Plus进阶:自定义主题(变量覆盖)+ 全局配置与组件按需加载优化
前端·javascript·vue.js
A黄俊辉A9 小时前
vue css中 :global的使用
前端·javascript·vue.js
小码哥_常9 小时前
被EdgeToEdge适配折磨疯了,谁懂!
前端