1

我试图在使用原型继承(我以前没有真正玩过)的同时解决这个上下文问题。我有一个 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”。

我知道上下文是一个相当基本的概念,我似乎对此一无所知。关于如何解决这个问题的任何想法?

4

3 回答 3

0

改成start这样:

start: function() {
    if (this.timer != null) {
        return;
    }
    var that = this;
    this.timer = setInterval(function() { that.move(); }, 3000);
    console.log("start");
}
于 2010-07-22T12:31:45.130 回答
0

我终于解决了......我在按钮点击中使用了一个闭包,如下所示:

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

并且还实现了上面 SimpleCoder 提到的改变。

于 2010-07-22T14:26:42.300 回答
0

您还可以在 setInterval 方法中传递当前对象实例,以便它始终可以访问“this”。

在 IE11、Chrome、Opera 和 Firefox 上验证。

setInterval(function (objRef) {              
        objRef.foo();
    }, 500, ***this***);
于 2016-08-06T07:48:33.283 回答