[英]How to pass parameters when calling a function without the parenthesis [Javascript]
I have a function called "tryMe" and I'm calling it without the parenthesis not precisely this but the idea is like what you would do here: 我有一个名为“tryMe”的函数,我在没有括号的情况下调用它而不是这个,但这个想法就像你在这里做的那样:
setTimeout(tryMe,200);
how can I pass parameters that I need? 如何传递我需要的参数?
I am using a jquery plugin that enables me to call a function but I have to call it withou the parenthesis or it executes itself upon loading. 我正在使用一个jquery插件,它允许我调用一个函数,但我必须用括号调用它,或者它在加载时自行执行。
setTimeout(function() { tryMe(parm1, parm2); }, 200);
A more robust offering, to ensure that the values of
parm1
,
parm2
don't change before the timeout fires (per @lincolnk's comment):
一个更强大的产品,以确保
parm1
,
parm2
的值在超时触发之前不会发生变化(根据@ lincolnk的评论):
setTimeout(function() { var p1 = parm1; var p2 = parm2; tryMe(p1, p2); }, 200);
@patrick dw, you're right, has to be evaluated before. @patrick dw,你是对的,必须先评估。
You can wrap tryMe
in a closure. 你可以在一个闭包中包装tryMe
。
For example: 例如:
var f = function(){tryMe('some parameter');};
setTimeout(f, 200);
Here, we create a function object, f
, which calls tryMe
with the desired parameter(s). 在这里,我们创建一个函数对象f
,它使用所需的参数调用tryMe
。 Then we pass f
to setTimeout
. 然后我们将f
传递给setTimeout
。 When the timeout expires, f
will be called, which will in turn call tryMe
with the desired parameters. 超时到期时,将调用f
,然后调用带有所需参数的tryMe
。
A word of warning if you wish to pass in parameters that may change before the timeout gets called (for example, if you are setting several timeouts in a for
loop): you will want to bind those variables like so: 如果您希望传入可能在调用超时之前更改的参数(例如,如果您在for
循环中设置多个超时),则会发出警告:您将要绑定这些变量,如下所示:
var f = function(someParamter){return function(){tryMe(someParameter);};};
setTimeout(f(someParameter), 200);
The reason simply doing something like 简单地做某事的原因
setTimeout(tryMe('some parameter'), 200); //Does not work.
doesn't work is because you are passing the result of evaluating tryMe
instead of the function object tryMe
itself. 不起作用是因为你传递的是评估tryMe
而不是函数对象tryMe
本身的结果。
You are not calling the function, the browser does - after 200 milliseconds. 你没有调用这个函数,浏览器会在200毫秒之后调用它。 You are merely providing it with the function that needs being called. 您只是向它提供需要被调用的函数。 Firefox actually allows specifying additional parameters in the setTimeout
call: Firefox实际上允许在setTimeout
调用中指定其他参数:
setTimeout(tryMe, 200, "first parameter", "second parameter");
However, as far as I know no other browsers support this feature so you should really use a closure function as explained by other answers already. 但是,据我所知,没有其他浏览器支持此功能,因此您应该使用封闭功能,如其他答案已解释的那样。 Here you create a temporary function with the sole purpose of calling your original function with the right parameters. 在这里,您可以创建一个临时函数,其唯一目的是使用正确的参数调用原始函数。
setTimeout(function() {tryMe("first parameter", "second parameter")}, 200);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.