博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript中的call()和apply()
阅读量:2509 次
发布时间:2019-05-11

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

call() and apply() are two functions that JavaScript offers to perform a very specific task: call a function and set its this value.

call()和apply()是JavaScript提供的用于执行特定任务的两个函数:调用一个函数并设置其this值。

Check out my to know all the details about this particular variable

查看我的以了解有关此特定变量的所有详细信息

A function can use the this value for many different use cases. The problem is that it’s given by the environment and cannot be changed from the outside, except when using call() or apply().

函数可以将this值用于许多不同的用例。 问题是它是由环境提供的,除非使用call()apply() ,否则不能从外部进行更改。

When using those methods, you can pass in an additional object that will be used as this in the function invoked.

使用这些方法时,可以传入一个附加对象,该对象将在调用的函数中用作this对象。

Those functions perform the same thing, but have a difference. In call() you can pass the function parameters as a comma separated list of parameters, taking as many parameters as you need, while in apply() you pass a single array that contains the parameters:

这些功能执行相同的操作,但有所不同。 在call()您可以将函数参数作为逗号分隔的参数列表进行传递,并根据需要获取尽可能多的参数,而在apply()您传递包含参数的单个数组:

const car = {  brand: 'Ford',  model: 'Fiesta'}const drive = function(from, to, kms) {  console.log(`Driving for ${kms} kilometers from ${from} to ${to} with my car, a ${this.brand} ${this.model}`)}drive.call(car, 'Milan', 'Rome', 568)drive.apply(car, ['Milan', 'Rome', 568])

Note that when using this is not bound, so this method only works with regular functions.

请注意,在使用 this 不受限制,因此该方法仅适用于常规功能。

翻译自:

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

你可能感兴趣的文章
C#调用C++编译的DLL详解
查看>>
Kali Linux的安装
查看>>
我的大学生活-5-08-赵心宁
查看>>
bzoj1708[Usaco2007 Oct]Money奶牛的硬币(背包方案数dp)
查看>>
P2700逐个击破(并查集/树形dp)
查看>>
python几大排序算法
查看>>
hdu 4619 二分图最大匹配 ——最大独立集
查看>>
VM CentOS 问题汇总
查看>>
这段时间的小结
查看>>
ANDROID_MARS学习笔记_S01原始版_021_MP3PLAYER001_下载mp3文件
查看>>
SQLServer视图
查看>>
入门阶段
查看>>
Android中使用http协议访问网络
查看>>
vs win32 & MFC 指针默认位置
查看>>
Join 与 CountDownLatch 之间的区别
查看>>
js存cookie
查看>>
vc6下dll调试
查看>>
Ubuntu apt常用命令
查看>>
struts2 配置(部分)
查看>>
python代码迷之错误(ModuleNotFoundError: No module named 'caffe.proto')
查看>>