プロトタイプの継承を使用しながら、このコンテキストの問題に頭を悩ませようとしています(これまで実際に遊んだことはありません)。私は AutoScroller オブジェクトを持っています:
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");
}
};
ドキュメントの準備ができたら、次のようにしてすべてを開始します。
var scr = new AutoScroller();
$('div.gallery p.stopBtn').bind("click", scr.stop);
$('div.gallery p.startBtn').bind("click", scr.start);
「this」は常にscrではなく「p.startBtn」を参照するため、すべての問題が発生します。そのため、setIntervalを使用した開始関数が呼び出されると、「this.move()は関数ではありません」というエラーが発生します。
コンテキストはかなり基本的な概念であり、私にはわからないようです。これを整理する方法についてのアイデアはありますか?