簡體   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