JavaScript中的匿名函数存在问题
这将显示:JavaScript中的匿名函数存在问题,javascript,parameters,anonymous-function,Javascript,Parameters,Anonymous Function,这将显示: 试验 试验 另一个测试 试验 指定为onBeforeLoad的反匿名函数中的alert()会一直显示“test”。我试试这个: jQuery.fn.testeee = function(_msg) { alert(_msg); $(this[0]).overlay({ onBeforeLoad: function() { alert(_msg); } }).load(); }; $
- 试验
- 试验
- 另一个测试
- 试验
jQuery.fn.testeee = function(_msg)
{
alert(_msg);
$(this[0]).overlay({
onBeforeLoad: function()
{
alert(_msg);
}
}).load();
};
$("#popup").testeee ('test');
$("#popup").testeee ('another_test');
而且效果很好。它显示:
- 试验
- 试验
- 试验
- 试验
有人知道为什么会发生这种情况吗?如果创建这样的对象:
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
}
当您调用不同元素的受试者时会发生什么?如果元素上已经有一个值,那么overlay可能不会创建新的值?那么,为什么在第一个示例中,函数alert()(由匿名函数调用)一直显示_msgtest的第一个值,而不是显示在下一次调用中实际传递的值(本例中是另一个_test)?
{
onBeforeLoad: function() { static_func(_msg) }
}