算是对 JS 的补充吧,也是核心内容。和大家聊聊 ES6 里那些最 “甜” 的语法糖,以及它们如何让我们的开发效率翻倍。

一、箭头函数:少写一行是一行

ES5 里写函数,不管多简单都得敲function关键字,还得时刻注意this的指向。而箭头函数(=>)就像一把 “语法剪刀”,直接剪掉了冗余的代码。

ES5 写法

const double = function(num) {
  return num * 2;
};

// 甚至匿名函数还要多敲几个字符
const numbers = [1, 2, 3];
const doubled = numbers.map(function(n) {
  return n * 2;
});

ES6 箭头函数

​// 单个参数可省略括号,单行返回可省略return和大括号
const double = num => num * 2;

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);

更爽的是,箭头函数里的this会 “继承” 自外层作用域,再也不用写const that = this这种 “黑魔法” 了。比如在 Vue 组件里处理事件:

​// ES5里的this坑
const obj = {
  name: "Allen",
  sayHi: function() {
    setTimeout(function() {
      console.log(this.name); // 这里的this指向window,输出undefined
    }, 1000);
  }
};

// ES6箭头函数拯救你
const obj = {
  name: "Allen",
  sayHi: function() {
    setTimeout(() => {
      console.log(this.name); // this继承自sayHi,输出"Allen"
    }, 1000);
  }
};

二、解构赋值:像 “拆快递” 一样提取数据

以前从对象或数组里拿数据,得一个个声明变量,代码像 “老太婆的裹脚布”。解构赋值就像给数据 “拆快递”,一次性把需要的东西全拿出来。

对象解构:按需提取,还能重命名

const user = {
  name: "Allen",
  age: 30,
  address: { city: "Beijing", street: "Main St" }
};

// ES5:一个个拿,累!
const userName = user.name;
const userAge = user.age;
const userCity = user.address.city;

// ES6:一行搞定,还能给变量重命名
const { name: userName, age, address: { city } } = user;
console.log(userName); // "Allen"
console.log(age); // 30
console.log(city); // "Beijing"

数组解构:按位置 “对号入座”

​const [first, second, ...rest] = [10, 20, 30, 40, 50];
console.log(first); // 10
console.log(second); // 20
console.log(rest); // [30, 40, 50] (剩余元素用...收集)

我在项目里最常用它处理接口返回值,比如后端返回一个复杂对象,前端只需要其中几个字段,用解构赋值瞬间清爽。

三、模板字符串:字符串拼接的 “终极解法”

谁没写过"Hello, " + name + "! You are " + age + " years old."这种代码?拼接一多,引号和加号能绕地球一圈。模板字符串(`)直接把变量 “塞” 进字符串里,还支持换行,简直是救星。

const name = "Allen";
const age = 30;

// ES5:拼接地狱
const info = "Hello, " + name + "! You are " + age + " years old.\n" + 
  "Today is " + new Date().toLocaleDateString() + ".";

// ES6:用${}嵌入变量,反引号支持换行
const info = `Hello, ${name}! You are ${age} years old.
Today is ${new Date().toLocaleDateString()}.`;

甚至还能在${}里写表达式,比如计算、调用函数:

const price = 99;
const count = 3;
const total = `总价:${price * count} 元(${count > 2 ? '含折扣' : '无折扣'})`;
console.log(total); // "总价:297 元(含折扣)"

四、默认参数:给函数参数 “上保险”

以前给函数参数设默认值,得先检查参数是否为undefined,写多了像 “废话文学”。ES6 直接在参数列表里定义默认值,简洁到离谱。

ES5 写法

function greet(name, message) {
  // 检查参数是否存在,不存在就用默认值
  name = name || "Guest";
  message = message || "Hello";
  return `${message}, ${name}!`;
}

ES6 默认参数

​// 直接在参数后加=设置默认值
function greet(name = "Guest", message = "Hello") {
  return `${message}, ${name}!`;
}

greet(); // "Hello, Guest!"
greet("Allen"); // "Hello, Allen!"
greet("Allen", "Hi"); // "Hi, Allen!"

更妙的是,默认参数还能依赖前面的参数,比如:

​function buildUrl(path, baseUrl = "https://api.example.com") {
  return `${baseUrl}/${path}`;
}
buildUrl("users"); // "https://api.example.com/users"

五、展开 / 剩余运算符:数组和对象的 “万能工具”

...运算符堪称 ES6 的 “瑞士军刀”,既能 “展开” 数组 / 对象(把元素一个个拆出来),又能 “收集” 剩余元素(把多个元素打包成数组),用法灵活到爆。

展开运算符:拆分集合

  • 合并数组:
    ​const arr1 = [1, 2, 3];
    const arr2 = [4, 5, ...arr1]; // [4, 5, 1, 2, 3]
  • 复制数组(避免引用问题):
    ​const original = [1, 2, 3];
    const copy = [...original]; // 等价于original.slice(),但更短
  • 传递多个参数给函数:
    ​const numbers = [1, 5, 3];
    const max = Math.max(...numbers); // 等价于Math.max(1,5,3),输出5
  • 合并对象(覆盖重复键):
    const user = { name: "Allen", age: 30 };
    const updatedUser = { ...user, age: 31, city: "Beijing" };
    // { name: "Allen", age: 31, city: "Beijing" }

剩余运算符:收集剩余元素

...用在函数参数或解构中时,它会把多个元素 “打包” 成数组:

​// 函数参数:收集所有传入的参数
function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6

// 解构:收集剩余元素
const [first, ...rest] = [10, 20, 30];
rest; // [20, 30]

六、class 语法:告别 “原型继承” 的混乱

ES5 用原型实现继承,代码又长又绕,新手看一眼能直接劝退。ES6 的class语法糖把继承变得像 “写作文” 一样直观,虽然底层还是原型,但写法上亲切多了。

ES5 原型继承

​// 父类
function Animal(name) {
  this.name = name;
}
Animal.prototype.sayName = function() {
  console.log(this.name);
};

// 子类
function Dog(name, breed) {
  Animal.call(this, name); // 继承属性
  this.breed = breed;
}
// 继承方法
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
  console.log("Woof!");
};

ES6 class 语法

​// 父类
class Animal {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log(this.name);
  }
}

// 子类:用extends继承,super调用父类构造器
class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 必须先调用super
    this.breed = breed;
  }
  bark() {
    console.log("Woof!");
  }
}

是不是清爽多了?我在写 React 组件或工具类时,几乎全用class,逻辑一目了然。

写在最后:语法糖不只是 “糖”

刚开始用 ES6 时,我以为这些语法糖只是 “让代码好看点”,但用得越久越发现:它们其实在 “强制” 我们写更规范的代码。比如箭头函数减少了this的混乱,解构赋值让数据提取更明确,默认参数避免了参数检查的冗余。

现在我的项目里,ES6 语法覆盖率已经超过 95%,代码量比以前减少了近 30%,同事们 review 代码时也能更快看懂逻辑。如果你还在犹豫要不要用 ES6,听我的:从今天开始,试着把function换成箭头函数,把+拼接换成模板字符串 —— 相信我,你会爱上这种 “甜” 的。

👋

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐