这是我正在尝试做的并且它不起作用,它显示的错误是:this.run不是一个函数。在线上(this.xId = window.setInterval('this.run()',2500);)
function(){
this.run = function(){
DO SOMETHING;
}
this.xId = window.setInterval( 'this.run()', 2500 );
}
可能是什么原因?
答案 0 :(得分:1)
您需要匿名传递该功能:
this.xId = window.setInterval( function() { this.run() }, 2500 );
或者更好的是bind此函数与this
上下文:
this.xId = window.setInterval( this.run.bind(this) , 2500 );
请注意,bind
是在ECMA-262第5版中实现的,因此对于crossbrowser兼容性,您需要添加以下内容:
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;
};
}
答案 1 :(得分:0)
首先,use a function reference rather than a string用于超时回调。使用字符串时this
是全局对象,而不是可能提供它的内容。
其次,缓存this
的值。回调中的this
可能与其外部的run
不同(与function(){
var that = this; //cache "this"
this.run = function(){
//DO SOMETHING;
}
this.xId = window.setInterval(function(){
that.run()
},2500);
}
附加的那个)。
{{1}}