内联函数和其他方法的范围

时间:2009-04-27 07:14:17

标签: javascript scope inline

如何在.ready()事件中为内联函数显示函数?

$(document).ready(function() {
  ...stuffs...
  myFunction(par1, par2, anotherFucntion_callback);
 }
);

function anotherFunction_callback(data) {
 ..stuffs..
}

2 个答案:

答案 0 :(得分:1)

您使用该函数的实际名称,即myFunction_callback而不是myFunctionanotherFucntion_callback

答案 1 :(得分:1)

我没有抓住你的问题。你的意思是你要传递“myFunction_callback(data)”作为你的最后一个参数:

myFunction(par1, par2, anotherFunction_callback);

,包括那个“数据”参数?

在这种情况下,解决方案非常标准,在此之前写下:

var temp = function() { anotherFunction_callback(data) };

另一种语法是:

function temp() { myFunction_callback(data) };
// even though this looks just like a free function,
// you still define it inside the ready(function())
// that's why I call it "alternative". They are equivalent.

通常,如果要将具有1个或多个参数的函数传递给另一个函数,则使用该格式。在这里,我们基本上创建一个新的无参数函数,调用另一个。新函数可以访问“data”变量。它被称为“封闭”,您可能想要阅读更多内容。 当然,如果回调不需要参数,您只需使用原始函数名称。

我希望这会有所帮助。

ps:您甚至可以内联函数声明,使其匿名,如下所示:     myFunction(par1,par2,function(){myFunction_callback(data)}); 注意

$(document).ready(function() {});

看起来就像那样。