Rest Parameter, Spread Oprator, Arrow Func
- Rest Parameter
假设有一个方法,我们希望可以这样调用它:

如果使用es5的方法,我们可能会这样实现它:

这样写有两个问题:
- 让人误以为这个方法不接受参数
- 任何对方法签名的修改,都有可能会让代码崩溃。比如说,添加了一个参数:

解决:
rest parameter syntax

三个点的语法可以把我们传进来的所有参数转换成一个数组。注意,rest parameter 必须是方法签名里的最后一个参数。
- spread oprator
假设我们的数据是从一个请求中返回来的,如下:

这里我们得到的tags是一个数组,而我们之前的displayTags方法接收的是一个个单独的参数,那怎么做呢?如下:


在这里,这三个点成为spread operator. 它可以使一个数组对象拆分成一个个的单独的元素。这个语法和之前的rest Parameter里的一样,但这次它是用在方法调用中,而不是方法定义中。(注意两个语法一样,但作用不一样,取决于它用在什么地方)

- arrow function
首先,我们对上面的功能做一个小封装:

我们知道,红色线圈起来的这个this 在调用时会失败,因为它在回调函数里,这时函数的执行环境的this已经不是TagComponent对象了。
解决方法:

箭头函数有词法作用域绑定作用,就是说他的作用域是取决于它被定义的地方,而不是运行时才决定的。如上,这个箭头函数就是定义在TagComponent对象中的。
Classes
ES5下,利用构造函数生成对象的方法。通过将方法添加到构造函数的prototype上来实现公用的目的。

在ES2015中,我们可以使用新class的语法来写出更加简便的面向对象的Javascript 。(Using the New Class Syntax)

注意,设置在constructor方法中的变量可以被class中的其他方法访问到。(Instance variables set on the constructor method can be accessed from all other instance method in the class)

注意,class的语法并不是引入了新的 JavaScript 对象模型,它只是基于目前存在的基于prototype实现继承方式的语法糖。它做的事情,实现的效果还是和之前的一模一样,只不过语法上改变了而已。(It's just the sweet way to write the same thing)

Class Inheritance
我们可以使用class的继承来减少代码重复。子类可以继承并指定定义在父类中的行为。extends关键字可以用来创建一个从其他类继承方法和属性的类。super方法可以运行父类里的constructor方法,基本上我们在每一个子类的constructor方法里第一行都会调用super()。子类也可以通过super对象来调用父类里的方法。


网友评论