setTimeout和closure

时间:2012-10-31 18:58:48

标签: javascript settimeout

有人可以解释为什么Eg1在FF中工作但在IE中不工作,为什么Eg2在FF和IE中都有效?

为Eg1

// ----- works in FF, not in IE   
var msg = "Hello World";
setTimeout(doAlert, 1, msg);
function doAlert(msg)
{
    alert(msg);
}

为Eg2

// ------ works in both IE, FF
var msg = "Hello World";
setTimeout(function() {doAlert(msg);}, 1);
function doAlert(msg)
{
    alert(msg);
}

1 个答案:

答案 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