2012-09-12 98 views
1

我正在嘗試使用一個setTimeout函數來調用它自己並被一個計數器打破。但是,我一直gettng一個NaN錯誤。有人能幫我嗎?當調用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

從setInterval運行函數時,「this」變量中的上下文不是您的對象,而是「window」對象。你需要通過上下文的方式如下:

setTimeout(this.increment_test.apply(this), 30) 
+1

我想你的意思'this.increment_test.bind(本)'。 –

1

setTimeout調用一個函數,它改變其window上下文。所以,increment_testthis不是你想象的那樣。

你需要做的是這樣的:

var self = this; 
setTimeout(function(){ 
    self.increment_test(); 
}, 30); 
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); 
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(); 
相關問題