In JavaScript sometimes we can chain method calls, like this:
在JavaScript中,有时我们可以链接方法调用,如下所示:
car.start().drive()
It’s pretty convenient to do so.
这样做非常方便。
Instead of writing
而不是写
car.start()
car.drive()
we can simplify in a one-liner.
我们可以简化一线。
This is possible if each method returns the object itself. In other words, the implementation must be something like this:
如果每种方法都返回对象本身,则可能发生这种情况。 换句话说,实现必须是这样的:
const car = {
start: function() {
console.log('start')
return this
},
drive: function() {
console.log('drive')
return this
}
}
It’s important to note that you can’t use arrow functions, because this
in an arrow function used as object method is not bound to the object instance.
需要特别注意的是,您不能使用箭头函数,因为在用作对象方法的箭头函数中, this
函数未绑定到对象实例。
I like to use arrow functions all the time, and this is one of the cases where you can’t.
我喜欢一直使用箭头功能,这是您无法使用的情况之一。
Chained method calls are great when you are not returning a set of values from the method, otherwise you obviously need to assign a method call to a variable, and chaining is not possible:
当您不从方法返回一组值时,链式方法调用非常有用,否则您显然需要将方法调用分配给变量,并且链式是不可能的:
const result = car.start()
if (result) {
car.drive()
}