为什么Firefox(v16)中没有以下工作?
var t = setTimeout(foo(), 1000);
我在控制台中遇到的错误是:“无用的setTimeout调用(参数周围缺少引号?)”。将它包装在引号中似乎没什么用,除了使它呈现为字符串(不出所料)。
然而,当我将它包装在如下的匿名函数中时它确实工作正常:
var t =
setTimeout(function(){
foo();
}, 1000);
但为什么有必要呢?为什么它不会在Webkit或Opera中爆炸?幸运的中风?
答案 0 :(得分:10)
因为你在第一个例子中调用了foo
。
与此基本相同:
var tempResultOfFoo = foo();
var t = setTimeout(tempResultOfFoo, 1000);
答案 1 :(得分:0)
将方法传递给setTimeout()
时,它将在全局范围内执行。 this
会在执行时指向window
。阅读更多HERE。
如果foo
不是全球性的,则无法找到它,而是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);
};