使用带有原型的 setInterval 的 JavaScript 上下文问题 [英] JavaScript context issue using setInterval with prototype

查看:48
本文介绍了使用带有原型的 setInterval 的 JavaScript 上下文问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在使用原型继承(我以前没有真正玩过)的同时解决这个上下文问题.我有一个 AutoScroller 对象:

I'm trying to get my head round this context problem while using prototypal inheritence (which I've not really played with before). I have an AutoScroller object:

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");
    }

};

文档准备好后,我会通过以下方式启动一切:

On document ready, I initiate everything by doing this:

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".

The problems all arise because "this" always refers to 'p.startBtn' and not scr, so when the start function with setInterval is called I'm getting an error "this.move() is not a function".

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

I know context is a fairly fundamental concept of which I appear to have no idea. Any ideas on how to sort this out?

推荐答案

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

You can also pass the current object instance in setInterval method, so that it always has the access to 'this'.

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

Verified on IE11, Chrome, Opera and Firefox.

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

这篇关于使用带有原型的 setInterval 的 JavaScript 上下文问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆