1

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

4

2 回答 2

3

要使用参数传递要执行的函数,可以使用 lambda。lambda 作为参数传递func

示例:(这是调用caller- textwhodowhat和是参数/变量。由于闭包mycode, lambda 仍然可以访问whodowhat和)mycode

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

至于“那个匿名函数会被调用两次吗?”,如果我明白你的意思,不会。也许你见过类似的语法

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

这是一个在创建后立即调用的 lambda(注意“调用”lambda 末尾的括号)。在第一个示例中,您只创建和传递匿名函数(函数是Javascript 中的第一类对象)。

于 2013-06-22T23:56:38.090 回答
2

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

caller(text, $.proxy(whathappen, this, who, dowhat, mycode));
于 2013-06-22T23:57:12.753 回答