返回

ES6修炼之let、const、arrow function、class

前端

ES6内功修炼之let、const、arrow function、class

ES6是JavaScript的最新版本,它引入了许多新的特性,使JavaScript更加强大和易于使用。ES6的这些新特性包括:

  • let和const
  • 箭头函数
  • class
  • 模块
  • 生成器

本文将介绍ES6的这几个新特性,并通过例子说明如何使用它们。

let和const关键字

let和const关键字是ES6中用于声明变量的新关键字。let声明的变量是块级作用域,而const声明的变量是常量。

// let声明的变量是块级作用域
let x = 10;
{
  let x = 20;
  console.log(x); // 输出20
}
console.log(x); // 输出10

// const声明的变量是常量
const y = 10;
y = 20; // 报错:TypeError: Assignment to constant variable.

箭头函数

箭头函数是ES6中引入的新函数语法。箭头函数与普通函数的不同之处在于:

  • 箭头函数没有自己的this关键字
  • 箭头函数没有自己的arguments对象
  • 箭头函数不能使用yield关键字
// 普通函数
function add(x, y) {
  return x + y;
}

// 箭头函数
const add = (x, y) => x + y;

console.log(add(1, 2)); // 输出3

class

class是ES6中引入的新语法,它允许我们创建自己的类。类是一种数据类型,它可以用来创建对象。

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

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const person = new Person('John Doe', 30);
person.greet(); // 输出:Hello, my name is John Doe and I am 30 years old.

模块

模块是ES6中引入的新特性,它允许我们把代码组织成不同的模块。模块可以被导入到其他模块中,也可以被导出供其他模块使用。

// myModule.js
export function add(x, y) {
  return x + y;
}

// main.js
import { add } from './myModule.js';

console.log(add(1, 2)); // 输出3

生成器

生成器是ES6中引入的新特性,它允许我们创建迭代器。迭代器是一种对象,它可以被用来遍历一个集合。

function* fibonacci() {
  let a = 0, b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const fibonacciGenerator = fibonacci();

for (const number of fibonacciGenerator) {
  if (number > 100) {
    break;
  }

  console.log(number); // 输出:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
}

总结

ES6是JavaScript的最新版本,它引入了许多新的特性,使JavaScript更加强大和易于使用。本文介绍了ES6的几个新特性,包括:

  • let和const关键字
  • 箭头函数
  • class
  • 模块
  • 生成器

这些新特性可以帮助我们编写更简洁、更易维护的JavaScript代码。