2012-05-24 37 views
0

這正是我試圖做的,它不工作,錯誤時被顯示爲:this.run不是一個函數。上線(this.xId = window.setInterval( 'this.run()',2500);)從調用在JavaScript中類中的一個類函數,jQuery的

function(){ 

    this.run = function(){ 

     DO SOMETHING; 

    } 

    this.xId = window.setInterval('this.run()', 2500); 

} 

可能是什麼原因?

+0

由於字符串' 「this.run()」'在全局範圍內進行評估,在那裏,'this'指'window'。我假設你在全局範圍內沒有'run'函數。 –

回答

1

您需要匿名傳遞函數,該函數:

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; 
    }; 
} 
+0

函數是否可以像這樣調用'window.setInterval(this.run,2500)'?;如果不能解釋區別? –

+0

我認爲錯誤的上下文,更新了答案 – antyrat

+0

綁定版本的工作,謝謝。但是我對「ECMA-262,第5版」感到困惑,我應該在哪裏添加它? – Xero

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

作爲一種替代「緩存的'this'值」您可以使用綁定功能:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#With_setTimeout – Nimphious

相關問題