3

为什么以下内容在 Firefox (v16) 中不起作用?

var t = setTimeout(foo(), 1000);

我在控制台中得到的错误是:“无用的 setTimeout 调用(参数周围缺少引号?)”。用引号括起来似乎没什么用,除了让它呈现为一个字符串(不足为奇)。

但是,当我将它包装在这样的匿名函数中时,它确实可以正常工作:

var t =
    setTimeout(function(){
       foo();
     }, 1000);

但为什么有必要?为什么它在 Webkit 或 Opera 中不爆炸?碰运气?

4

2 回答 2

10

这是因为您在第一个示例中调用foo

它与这样做基本相同:

var tempResultOfFoo = foo();
var t = setTimeout(tempResultOfFoo, 1000);
于 2012-11-13T20:07:58.463 回答
0

当您将方法传递给 时setTimeout(),它将在全局范围内执行。 this将指向window执行时。在这里阅读更多。

如果foo不是全局的,则不会被找到,ergo ReferenceError

var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
// just backed up the defaults. Now basically creating timeout and setInterval
//functions that take scope as a parameter,
//so you can use them in whichever invocation context you want.

window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeST__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};

window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeSI__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};
于 2012-11-13T20:11:11.300 回答