JavaScript中的链接方法调用

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()
}

翻译自: https://flaviocopes.com/javascript-chaining/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值