我試圖在使用原型繼承(我以前沒有真正使用過)的同時讓我的頭繞過這個上下文問題。我有一個自動滾動對象:使用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()不是一個函數」。
我知道上下文是一個相當基本的概念,我似乎不知道。任何想法如何解決這個問題?
不幸的是我已經嘗試過這種方法 - 執行「即=導致該變種」,即= p.startBtn行後 – user399050 2010-07-22 13:28:33
對不起,這實際上是正確的(仍然!)。但是,它需要與我在此處放置的按鈕單擊事件關聯使用。感謝您的回覆。 – user399050 2010-07-22 14:31:22