2010-07-22 58 views
1

我試圖在使用原型繼承(我以前沒有真正使用過)的同時讓我的頭繞過這個上下文問題。我有一個自動滾動對象:使用setInterval和原型的JavaScript上下文問題

var scr = new AutoScroller(); 
$('div.gallery p.stopBtn').bind("click", scr.stop); 
$('div.gallery p.startBtn').bind("click", scr.start); 

的問題會出現,因爲「這」通常是指「p.startBtn」,而不是SCR:

function AutoScroller() { 
    this.timer = null; 
} 

AutoScroller.prototype = { 

    stop: function() { 
     if (this.timer == null) { 
      return; 
     } 

     clearInterval(this.timer); 
     this.timer = null; 
     console.log("stop"); 
    }, 

    start: function() { 
     if (this.timer != null) { 
      return; 
     } 
     this.timer = setInterval(function() { this.move(); }, 3000); 
     console.log("start"); 
    }, 

    move: function() { 
     console.log("move"); 
    } 

}; 

在文件準備好,我做這一切開始,所以當啓動函數setInterval被調用時,我得到一個錯誤「this.move()不是一個函數」。

我知道上下文是一個相當基本的概念,我似乎不知道。任何想法如何解決這個問題?

回答

0

變化start這樣:

start: function() { 
    if (this.timer != null) { 
     return; 
    } 
    var that = this; 
    this.timer = setInterval(function() { that.move(); }, 3000); 
    console.log("start"); 
} 
+0

不幸的是我已經嘗試過這種方法 - 執行「即=導致該變種」,即= p.startBtn行後 – user399050 2010-07-22 13:28:33

+0

對不起,這實際上是正確的(仍然!)。但是,它需要與我在此處放置的按鈕單擊事件關聯使用。感謝您的回覆。 – user399050 2010-07-22 14:31:22

0

我終於摸索出來...我用的按鈕關閉點擊這樣的:

var scr = new AutoScroller(); 
$('div.gallery p.startBtn').bind('click', function(x) { 
    return function() { 
     x.start(); 
    } 
}(scr)); 

而且還實現由SimpleCoder提到的變化以上。

0

您也可以在setInterval方法中傳遞當前對象實例,以便它始終有權訪問'this'。

在IE11,Chrome,Opera和Firefox上進行驗證。

setInterval(function (objRef) {    
     objRef.foo(); 
    }, 500, ***this***);