使用setInterval和prototype的JavaScript上下文问题

时间:2010-07-22 12:27:32

标签: javascript prototype object setinterval

我正试图在使用原型继承(我之前没有真正使用过)的情况下解决这个问题。我有一个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()不是函数”。

我知道语境是一个相当基本的概念,我似乎不知道。关于如何解决这个问题的任何想法?

3 个答案:

答案 0 :(得分:0)

start更改为:

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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

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

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

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