在javascript中访问类外的函数
我的班级结构是这样的:在javascript中访问类外的函数,javascript,jquery,oop,Javascript,Jquery,Oop,我的班级结构是这样的: var jpTWUI = function(id, connection){ this.id = id; this.muteButton = "#mute"; this.hangupButton = "#hang"; this.transferButton = "#trans"; this.parentElement = jQuery('#timerCon'); this.connection = connection;
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(){...}
}
jpTWUI.prototype = {
…
startTimer: function(){
this.timer = setInterval(function(){
console.log("interval")
},2000) // every 2 seconds
},
stopTimer: function(){
if(this.timer){
clearInterval(this.timer);
}
}
}
现在我已经创建了一个对象,并像这样调用这个类
var callHandler = new jpTWUI('timerCon', connection);
callHandler.startTimer();
但问题是方法startTimer
具有setInterval
功能,该功能以分钟和秒为单位显示持续时间
我想实现另一种方法,比如stopTimer
停止startTimer
的间隔,我知道我必须使用窗口。clearInterval
。但是,当我在同一个类中实现函数stopTimer
时,我不知道如何使用以下类访问该方法:
var callHandler = new jpTWUI('timerCon', device);
callHandler.stopTimer();
希望你们理解我想要实现的目标,这是我第一次在javascript中使用这个类
请指导我这种做法是否正确??
或者如何使其正确。在创建时获取id并清除它
this.interval = setInterval(function(){..}, 1000)
clearInterval(this.interval );
这对您的问题有帮助吗?修改的代码。将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();
setInterval
返回一个标识符,您可以将该标识符传递到clearInterval
以停止计时器,因此您可以执行以下操作:
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(){...}
}
jpTWUI.prototype = {
…
startTimer: function(){
this.timer = setInterval(function(){
console.log("interval")
},2000) // every 2 seconds
},
stopTimer: function(){
if(this.timer){
clearInterval(this.timer);
}
}
}
在创建计时器时,应该在变量中获取它的id,并将其传递给clearfunction@AshokRaj我已经输入了变量
this.interval=setInterval(function(){..},1000)
,但我不知道如何将this.interval访问stopTimer()…我可以使用类似的东西吗<代码>var callHandler=new jpTWUI('timerCon',device);callHandler.startTimer()代码>和var callHandler=newjptwui('timerCon',device);callHandler.stopTimer()代码>是的,你可以。您正在重新创建jpTWUI对象吗?您应该只初始化callHandler一次。我可以这样做吗var callHandler=new jpTWUI('timerCon',device)
并单独调用这些方法,就像我要调用callHandler.startTimer()的条件一样在第二个条件中,我想调用callHandler.stopTimer()代码>这可能吗??