本文共 2701 字,大约阅读时间需要 9 分钟。
by Rajat Saxena
通过拉贾特·萨克森纳(Rajat Saxena)
I’m writing this micro post because the aforementioned question has haunted me for a very long time, and I knew I wasn’t the only one. Every single time I saw someone use any of those three methods I had to rush to in order to figure out what was going on.
我之所以写这篇微型文章,是因为上述问题困扰了我很长时间,而且我知道我并不是唯一的一个。 每当我看到有人使用这三种方法中的任何一种时,我都必须赶紧向进行操作以弄清发生了什么。
Enough was enough. I knew I had to do something and I did. I supposedly have created a proverbial silver bullet which can help new JavaScript developers out.
足够了。 我知道我必须做某事,而且我做到了。 据推测,我创造了一个众所周知的灵丹妙药,可以帮助新JavaScript开发人员。
Disclaimer: This is not a theoretical solution, but a really hacky way to remember the difference.
免责声明 :这不是理论上的解决方案,而是一种记住差异的真正卑鄙的方式。
The major cause of confusion between the call()
and apply()
methods is how to pass in the additional arguments besides this
. And why do we have bind()
anyway?
在混淆的主要原因call()
,并apply()
方法是如何在除了额外的参数传递this
。 为什么我们仍然有bind()
?
So let’s learn how to easily tell the three apart.
因此,让我们学习如何轻松区分这三个。
apply(this [, [arg1, arg2,...]])
: Calls a function with a provided this
value. Further arguments are provided as a single array.
apply(this [, [arg1, arg2,...]])
:使用提供的this
值调用一个函数。 其他参数作为单个数组提供 。
Way to remember: “Apply accepts arguments as an Array” or “AA”
的方式来记住 :“A pply接受参数为A rray”或“AA”
call(this [, arg1, arg2...])
: Calls a function with a provided this
. Further arguments are provided as a comma separated list
call (this [, arg1, arg2...])
:使用提供的this
调用函数。 其他参数以逗号分隔列表的形式提供
Ways to remember: “Call’s arguments are separated by commas” or “CC”.
记住方式: “ Call的参数用逗号分隔”或“ CC ”。
bind(this)
: Returns a new function whose this
value is bound to the provided value.
bind(this)
:返回一个新的函数,其this
值被绑定到所提供的值。
Ways to remember: bind() is the only method out of the three that returns a new function altogether. It does not call the function.
记住方式: bind()是这三个方法中唯一一个完全返回新函数的方法。 它不调用该函数。
I hope the above explanation might help some of you out there. It certainly is helping me.
希望以上解释对您有所帮助。 它肯定在帮助我。
Do you have other memorization tricks related to programming? Kindly share it with the community as it will help everyone out. Especially during those interviews.
您还有其他与编程有关的记忆技巧吗? 请与社区分享,因为它将帮助所有人。 特别是在那些采访中。
If you have any queries or doubts, hit me up on Twitter or write to me at . Please recommend this post, if you liked it and share it with your network.
如果您有任何疑问或疑问,请在Twitter 上打我,或给我写信至 。 如果喜欢,请推荐这篇文章,并与您的网络分享。
翻译自:
转载地址:http://abewd.baihongyu.com/