Skip to Content
开发🎨 前端开发Web 基础JavaScriptES6

ES6(也叫ES2015)是JavaScript的一次重大更新,给代码带来了很多方便的新功能。别被专业名词吓到,我们像拆快递一样,用生活化的例子解释这些新特性!


📦 快递1号:letconst —— 更安全的变量

以前用var声明变量,像没有房间号的储物柜,谁都能拿。现在:

  • let:像带锁的储物柜(块级作用域),只在当前房间有效
  • const:像贴了封条的储物柜(常量),声明后不能改
let age = 18; // 这个年龄可以改 const PI = 3.14; // 这个值固定不变!

🏹 快递2号:箭头函数 —— 写函数更省力

普通函数要写function,箭头函数直接=>搞定:

// 旧写法 function add(a, b) { return a + b; } // 新写法(像射箭一样简洁!) const add = (a, b) => a + b;

附加技能:箭头函数里的this会自动继承上下文,不用再写bind(this)


🧩 快递3号:模板字符串 —— 拼接文字超轻松

不用再写+号连接字符串,用反引号`包裹,变量用${}插入:

const name = "小明"; console.log(`你好,${name}!今天气温${25}℃`); // 打印:你好,小明!今天气温25℃

📦 快递4号:解构赋值 —— 拆包裹式取值

从对象或数组中直接提取值,像拆快递一样方便:

// 对象解构 const person = { name: '小红', age: 20 }; const { name, age } = person; // 拆出name和age // 数组解构 const colors = ['红', '黄', '蓝']; const [first, second] = colors; // first='红', second='黄'

☕ 快递5号:函数默认参数 —— 点咖啡自带加糖

函数参数可以设置默认值,就像点咖啡默认加一包糖:

function orderCoffee(type = '拿铁', sugar = 1) { return `一杯${type},加${sugar}包糖`; } orderCoffee(); // "一杯拿铁,加1包糖"

🧩 快递6号:模块化 —— 代码分块管理

把代码拆分成多个文件,像乐高积木一样组合使用:

// math.js export const add = (a, b) => a + b; // app.js import { add } from './math.js'; console.log(add(1,2)); // 3

⏳ 快递7号:Promise & async/await —— 优雅处理异步

告别回调地狱,用更直观的方式处理异步操作:

Promise版:

fetchData() .then(data => console.log(data)) .catch(error => console.error(error));

async/await版(更像写同步代码):

async function getData() { try { const data = await fetchData(); console.log(data); } catch (error) { console.error(error); } }

🎓 快递8号:Class类 —— 面向对象更清晰

class关键字定义类,继承也更简单:

class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name}发出声音`); } } class Dog extends Animal { speak() { console.log(`${this.name}汪汪叫!`); } }

🚀 学习建议

  1. 先掌握最常用的特性(箭头函数、解构、模板字符串)
  2. 多在项目中实践,比如用let/const替代var
  3. 遇到问题查文档,推荐 MDN ES6 教程

ES6就像给JavaScript装上了火箭推进器,让代码更简洁高效!现在就去写几行代码试试吧~ 🎉

Last updated on