我正在尝试使用setTimeout函数来调用自身并被计数器破坏。但是,我一直都会遇到NaN错误。有人能帮助我吗?
<script language="javascript">
function Tests() {
this.i = 0;
}
Tests.prototype.increment_test = function () {
if (this.i > 2) {
return;
}
alert(this.i);
this.i++;
setTimeout(this.increment_test, 30);
}
ta = new Tests();
ta.increment_test();
</script>
答案 0 :(得分:3)
this
未永久绑定到increment_test
函数。
您可以在变量中引用this
,并在匿名函数中使用它。
var self = this;
setTimeout(function() { self.increment_test()}, 30);
或者您可以使用Function.prototype.bind
将调用上下文绑定到函数。
setTimeout(this.increment_test.bind(this), 30);
或者你可以创建一个绑定上下文的小实用程序。
function _bindCtx(fn, ctx) {
return function() { return fn.apply(ctx); };
}
并像这样称呼它。
setTimeout(_bindCtx(this.increment_test, this), 30);
答案 1 :(得分:1)
setTimeout
调用函数时,会将其上下文更改为window
。因此,在increment_test
内,this
不是您认为的那样。
你需要这样做:
var self = this;
setTimeout(function(){
self.increment_test();
}, 30);
答案 2 :(得分:0)
从setInterval运行函数时,“this”变量中的上下文不是您的对象而是“window”对象。您需要以下列方式传递上下文:
setTimeout(this.increment_test.apply(this), 30)
答案 3 :(得分:0)
function Tests() {
this.i = 0;
// Next line added. I think what it's the best solution because it can
// increase the speed and reduce the consumption of resources (memory)
// when used with setTimeout()
this.increment_test = this.increment_test.bind(this);
}
Tests.prototype.increment_test = function () {
if (this.i > 2) {
return;
}
alert(this.i);
this.i++;
setTimeout(this.increment_test, 30);
}
ta = new Tests();
ta.increment_test();