
1.2 ES 6语法简介
ES 6是JavaScript语言的新一代标准,加入了很多新的功能和语法。React的项目一般都是用ES 6语法来写的,这也是Facebook官方推荐的方式。为保证本书知识体系的完整性,本节我们会对开发React应用经常用到的ES 6语法做简要介绍。
1.let、const
let和const是ES 6中新增的两个关键字,用来声明变量,let和const都是块级作用域。let声明的变量只在let命令所在的代码块内有效。const声明一个只读的常量,一旦声明,常量的值就不能改变。例如:

2.箭头函数
ES 6允许使用“箭头”(=>)定义函数。这种方式创建的函数不需要function关键字,并且还可以省略return关键字。同时,箭头函数内的this指向函数定义时所在的上下文对象,而不是函数执行时的上下文对象。例如:

如果箭头函数的参数多于1个或者不需要参数,就需要使用一个圆括号代表参数部分。例如:

如果函数体内包含的语句多于一条,就需要使用大括号将函数体括起来,使用return语句返回。例如:

3.模板字符串
模板字符串是增强版的字符串,用反引号(`)标识字符串。除了可以当作普通字符串使用外,它还可以用来定义多行字符串,以及在字符串中嵌入变量,功能很强大。例如:

4.解构赋值
ES 6允许按照一定模式从数组和对象中提取值,对变量进行赋值,这被称为解构。例如:

函数的参数也可以使用解构赋值。例如:

解构同样适用于嵌套结构的数组或对象。例如:

5.rest参数
ES 6引入rest参数(形式为...变量名)用于获取函数的多余参数,以代替arguments对象的使用。rest参数是一个数组,数组中的元素是多余的参数。注意,rest参数之后不能再有其他参数。例如:

6.扩展运算符
扩展运算符是三个点(...),它将一个数组转为用逗号分隔的参数序列,类似于rest参数的逆运算。例如:

扩展运算符还常用于合并数组以及与解构赋值结合使用。例如:

扩展运算符还可以用于取出参数对象的所有可遍历属性,复制到当前对象之中。例如:

7.class
ES 6引入了class(类)这个概念,新的class写法让对象原型的写法更加清晰,也更像传统的面向对象编程语言的写法。例如:

class之间可以通过extends关键字实现继承,例如:

8.import、export
ES 6实现了自己的模块化标准,ES 6模块功能主要由两个关键字构成:export和import。export用于规定模块对外暴露的接口,import用于引入其他模块提供的接口。例如:

本节介绍的ES 6语法是后面我们介绍React时经常用到的语法,且只介绍了最基本的用法,如果读者想了解ES 6完整的语法知识,请自行查阅相关文档学习。