[英]What to use - Passing context or call/apply?
In javascript, If I have to invoke a function in a different context, what is the preferred way to invoke the same. 在javascript中,如果我必须在不同的上下文中调用一个函数,那么调用它的首选方法是什么。 and why?
为什么?
1) Pass this
as a parameter like below: 1)
this
作为参数传递如下:
callthisfunction(arg1, arg2, this);
function callthisfunction(arg1, arg2, context) {}
OR 要么
2) Make use of call/apply like given below: 2)使用如下给出的电话/申请:
callthisfunction.call(this, arg1, arg2);
That depends on how the function works. 这取决于功能的工作原理。 If you are refering to the context by
this
, I would prefer the call
. 如果你通过
this
引用上下文,我更喜欢这个call
。
You can use context
, if you want to work with let's say the current and the passed scope. 您可以使用
context
,如果您想使用,请说出当前和已通过的范围。
You should maybe also take a look at this article . 你也许应该看看这篇文章 。 It describes
call
a little bit more in detail. 它更详细地描述了
call
。 Also apply might be useful for you in the future. 也适用于将来可能对您有用。
EDIT: Also take a look at this answer and the provided example . 编辑:另请查看此答案和提供的示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.