博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript中的链接方法调用
阅读量:2506 次
发布时间:2019-05-11

本文共 1170 字,大约阅读时间需要 3 分钟。

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

翻译自:

转载地址:http://gxmgb.baihongyu.com/

你可能感兴趣的文章
iView 的后台管理系统简易模板 iview-admin-simple
查看>>
写一个自己的搜索引擎(1)
查看>>
NGINX、PHP-FPM开机自动启动
查看>>
python 递归求阶乘
查看>>
ERROR: child process failed, exited with error number 100
查看>>
Java计算器源代码
查看>>
SQLServer视图
查看>>
《Entity Framework 6 Recipes》翻译系列 (3) -----第二章 实体数据建模基础之创建一个简单的模型...
查看>>
入门阶段
查看>>
游戏制作人的职能
查看>>
学生信息管理系统应用ios源码iPad版
查看>>
Android中使用http协议访问网络
查看>>
ASP.NET Core 菜鸟之路:从Startup.cs说起
查看>>
vs win32 & MFC 指针默认位置
查看>>
Join 与 CountDownLatch 之间的区别
查看>>
js存cookie
查看>>
vc6下dll调试
查看>>
Ubuntu apt常用命令
查看>>
struts2 配置(部分)
查看>>
python代码迷之错误(ModuleNotFoundError: No module named 'caffe.proto')
查看>>