【问题标题】:JavaScript context issue using setInterval with prototype使用带有原型的 setInterval 的 JavaScript 上下文问题
【发布时间】:2010-07-22 12:27:32
【问题描述】:

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

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

【问题讨论】:

    标签: javascript prototype object setinterval


    【解决方案1】:

    start 更改为:

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

    【讨论】:

    • 不幸的是我已经尝试过这种方法 - 在执行“var that = this”行之后,that = p.startBtn (still!)
    • 对不起,这实际上是正确的。但是,它需要与我在这里放置的按钮单击事件的闭包结合使用。感谢您的回复。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      您也可以在 setInterval 方法中传递当前对象实例,使其始终可以访问 'this'。

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

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

      【讨论】:

        猜你喜欢
        • 2011-07-05
        • 1970-01-01
        • 2012-07-05
        • 2015-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-06
        • 1970-01-01
        相关资源
        最近更新 更多