How to pass parameters when calling a function without the parenthesis [Javascript]

为君一笑 提交于 2019-12-10 03:39:50

问题


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:

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.


回答1:


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):

setTimeout(function() {
   var p1 = parm1;
   var p2 = parm2;
   tryMe(p1, p2);
}, 200);

@patrick dw, you're right, has to be evaluated before.




回答2:


You can wrap tryMe in a closure.

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). Then we pass f to setTimeout. When the timeout expires, f will be called, which will in turn call tryMe with the desired parameters.

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:

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.




回答3:


You are not calling the function, the browser does - after 200 milliseconds. You are merely providing it with the function that needs being called. Firefox actually allows specifying additional parameters in the setTimeout call:

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);


来源:https://stackoverflow.com/questions/7176292/how-to-pass-parameters-when-calling-a-function-without-the-parenthesis-javascri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!