简体   繁体   中英

Passing a function with parameters as parameter of another function

there a some similar questions, but im still confused. because my case is function with params as parameter to another function.

Simple case:

var who = 'Old IE',
dowhat  = 'eat',
mycode  = 'my code :(',
text    = 'I dont know why';

function whathappen(who, dowhat, mycode) {
    alert(who + dowhat + mycode);
}

function caller(text, func) {
    alert(text);
    func();
}

question: how to do something like caller(text, whathappen(who, dowhat, mycode)); ? im not sure if we use anonymous function like caller(text, function(){ ... } (would that anonymous func. called twice?)

Thank you

To pass a function to be executed with arguments, you can use a lambda. The lambda is passed as the parameter func .

Example: (this is the invocation of caller - text , who , dowhat , and mycode are parameters/variables. the lambda still has access to who , dowhat , and mycode because of closures )

caller(text, function () {
    whathappen(who, dowhat, mycode);
});

As for "would that anonymous func. called twice?", if I understand what you mean, no. Maybe you have seen syntax like

(function () {
    ...
})();

Which is a lambda that is called immediately after creation (notice the parenthesis at the end "invoking" the lambda). In the first example, you are only creating and passing the anonymous function (functions are first class objects in Javascript).

您可以使用proxy方法创建一个函数,该函数调用具有特定值的另一个函数:

caller(text, $.proxy(whathappen, this, who, dowhat, mycode));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM