我试图在使用原型继承(我以前没有真正玩过)的同时解决这个上下文问题。我有一个 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”总是指“p.startBtn”而不是 scr,所以当调用带有 setInterval 的 start 函数时,我得到一个错误“this.move() is not a function”。
我知道上下文是一个相当基本的概念,我似乎对此一无所知。关于如何解决这个问题的任何想法?