繁体   English   中英

在javascript类之外访问函数

[英]access functions outside the class in javascript

我的班级结构是这样的:

var jpTWUI = function(id, connection){
    this.id = id;
    this.muteButton = "#mute";
    this.hangupButton = "#hang";
    this.transferButton = "#trans";
    this.parentElement = jQuery('#timerCon');
    this.connection = connection;

    this.interval = "";

    this.createElements();
    this.addEvents(); 
};

jpTWUI.prototype = { 
    createElements: function(){ ... }, 
    addEvents: function(){...}, 
    startTimer: function(){...}
}

现在,我创建了一个对象,并将该类称为

var callHandler = new jpTWUI('timerCon', connection);
callHandler.startTimer();

但是问题在于方法startTimer具有setInterval函数,该函数以分钟和秒为单位显示持续时间。

我想实现另一种方法,如stopTimer ,该方法停止该startTimer的间隔,我知道我必须使用window.clearInterval 但是当我在同一个类中实现功能stopTimer ,我不知道如何使用类似的类来访问该方法:

var callHandler = new jpTWUI('timerCon', device);
callHandler.stopTimer();

希望大家理解我要实现的目标,这是我第一次使用javascript中的类。

请指导我这种方法是正确的吗? 或我如何使它正确。

修改后的代码。 将setInterval的返回值保存在setIntervalConst中,并使用它clearInterval。 在调用startTimer和stopTimer时,应使用jpTWUI的相同实例。

var callHandler = new jpTWUI('timerCon', connection);
callHandler.startTimer();

///var callHandler = new jpTWUI('timerCon', device); // remove this line if you want access same instance of jpTWUI.
callHandler.stopTimer();

jpTWUI.prototype = { 
    createElements: function(){ ... }, 
    addEvents: function(){...}, 
    setIntervalConst: 0,
    startTimer: function(){ this.setIntervalConst = setInterval(....) ....},
    stoptTimer: function(){ clearInterval(this.setIntervalConst ); ....}
}

在创建并获取ID时将其清除。

this.interval = setInterval(function(){..}, 1000)
clearInterval(this.interval );

这对您的问题有帮助吗?

setInterval返回一个标识符,您可以将该标识符传递给clearInterval来停止计时器,因此您可以执行以下操作:

jpTWUI.prototype = { 
    …
    startTimer: function(){
        this.timer = setInterval(function(){
            console.log("interval")
        },2000) // every 2 seconds
    },
    stopTimer: function(){
        if(this.timer){
            clearInterval(this.timer);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM