有人可以解释为什么Eg1在FF中工作但在IE中不工作,为什么Eg2在FF和IE中都有效?
// ----- works in FF, not in IE
var msg = "Hello World";
setTimeout(doAlert, 1, msg);
function doAlert(msg)
{
alert(msg);
}
// ------ works in both IE, FF
var msg = "Hello World";
setTimeout(function() {doAlert(msg);}, 1);
function doAlert(msg)
{
alert(msg);
}
答案 0 :(得分:0)
因为回调参数不是默认值。
要启用在IE上传递额外参数,请使用以下代码段:
if (document.all && !window.setTimeout.isPolyfill)
{
var __nativeST__ = window.setTimeout;
window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */)
{
var aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeST__(vCallback instanceof Function ? function ()
{
vCallback.apply(null, aArgs);
} :
vCallback, nDelay
);
};
window.setTimeout.isPolyfill = true;
}
if (document.all && !window.setInterval.isPolyfill)
{
var __nativeSI__ = window.setInterval;
window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */)
{
var aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeSI__(vCallback instanceof Function ? function ()
{
vCallback.apply(null, aArgs);
} :
vCallback, nDelay
);
};
window.setInterval.isPolyfill = true;
}
来源:https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout