您需要匿名傳遞函數,該函數:
this.xId = window.setInterval(function() { this.run() }, 2500);
或者更好的是bind此功能與this
方面:
this.xId = window.setInterval(this.run.bind(this) , 2500);
注意bind
在ECMA-262實現,第5版,所以對於跨瀏覽器兼容,你需要補充一點:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
由於字符串' 「this.run()」'在全局範圍內進行評估,在那裏,'this'指'window'。我假設你在全局範圍內沒有'run'函數。 –