jQuery.fn.testeee = function(_msg)
{
alert(_msg);
$(this[0]).overlay({
onBeforeLoad: function()
{
alert(_msg);
}
}).load();
};
$("#popup").testeee ('test');
$("#popup").testeee ('another_test');
这显示:
- 测试
- 测试
- 另一个测试
- 测试
分配给 onBeforeLoad 的匿名函数中的 alert() 一直显示“测试”。我试试这个:
jQuery.fn.testeee = function(_msg)
{
alert(_msg);
$(this[0]).overlay({
onBeforeLoad: static_func(_msg)
}).load();
};
function static_func(_msg)
{
alert(_msg);
}
$("#popup").testeee ('test');
$("#popup").testeee ('another_test');
而且效果很好。它显示:
- 测试
- 测试
- 测试
- 测试
有人知道为什么会发生这种情况吗?
最佳答案
如果你像这样创建一个对象:
{
onBeforeLoad: static_func(_msg)
}
它不指定要调用的函数,而是立即调用函数并将返回值存储在对象中。
要指定要调用的函数,您只需使用函数名称:
{
onBeforeLoad: static_func
}
如果你想用你自己指定的参数调用函数,你必须创建一个包含变量的闭包,方法是将它包装在一个匿名函数中:
{
onBeforeLoad: function() { static_func(_msg) }
}
关于javascript - 在 JavaScript 中使用匿名函数有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1397672/