Javascript:析构函数或类似的东西
我已经创建了这个小对象,当它涉及到间隔时非常方便,并且作为动画帧工作得非常好,但是它有一个小东西。如果对实例的引用丢失,则间隔将继续Javascript:析构函数或类似的东西,javascript,Javascript,我已经创建了这个小对象,当它涉及到间隔时非常方便,并且作为动画帧工作得非常好,但是它有一个小东西。如果对实例的引用丢失,则间隔将继续 function Interval(callback, interval){ var timer = null; this.start = function(){ if(!timer) timer = setInterval(callback, interval); }; this.stop = function()
function Interval(callback, interval){
var timer = null;
this.start = function(){
if(!timer) timer = setInterval(callback, interval);
};
this.stop = function(){
clearInterval(timer);
timer = null;
};
this.changeSpeed = function(a){
interval = a;
this.stop();
this.start();
}
this.destroy = function(){
delete this;
}
}
显然,如果javascript没有destruct方法,我就无法跟踪何时停止间隔,因此我想我应该创建一个destroy方法,但我不确定是否可以从对象内部销毁实例。这是有道理的,但是。。。感谢您的帮助 这样做怎么样:
function Interval(callback, interval){
var self = this;
var timer = null;
this.start = function(){
if(!timer) timer = setInterval(function() {
callback(self)
}, interval);
};
this.stop = function(){
clearInterval(timer);
timer = null;
};
this.changeSpeed = function(a){
interval = a;
this.stop();
this.start();
}
this.destroy = function(){
this.stop();
}
}
var foo = new Interval(function(i) {
// check if my interval is still needed
if (dontNeedItAnymore) {
i.destroy(); // or just .stop()
}
else {
// do whatever
}
}, 1000);
foo = null; // whoops, lost the reference, but the callback will still be able to reference it
现在,至少在调用回调时,它会将引用传递给您的对象,如果他们不再需要它,回调至少有机会停止它
这里的技巧是使用闭包来确保在间隔过期时仍然可以引用对象(因此使用self
变量)
所以现在我可以这样做:
function Interval(callback, interval){
var self = this;
var timer = null;
this.start = function(){
if(!timer) timer = setInterval(function() {
callback(self)
}, interval);
};
this.stop = function(){
clearInterval(timer);
timer = null;
};
this.changeSpeed = function(a){
interval = a;
this.stop();
this.start();
}
this.destroy = function(){
this.stop();
}
}
var foo = new Interval(function(i) {
// check if my interval is still needed
if (dontNeedItAnymore) {
i.destroy(); // or just .stop()
}
else {
// do whatever
}
}, 1000);
foo = null; // whoops, lost the reference, but the callback will still be able to reference it
问题是,为什么对实例的引用首先会丢失,如果丢失,您将如何在这种销毁方法中引用实例?+1表示您的(假)图片。。不,假照片??真正地我的投票已经被锁定了。哇@RakeshKR,这就是我所说的小编辑。@Streppel你是什么意思?一个点会有很大的不同(就像一张照片)!哈哈,现在我明白你的意思了。好吧,如果没有办法自动完成,那么我想这就是它能做到的。谢谢你,先生@伯吉:那是我剪切粘贴的OP代码。