当您将方法传递给 时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);
};