gpt4 book ai didi

Javascript:析构函数或类似的东西

转载 作者:行者123 更新时间:2023-11-29 15:39:12 27 4
gpt4 key购买 nike

我已经创建了这个小对象,它在涉及间隔时非常方便,并且作为动画帧工作得很好,但它有一些关于它的小东西。如果对实例的引用丢失,则间隔继续。

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

现在至少当回调被调用时它会传递一个对你的对象的引用并且回调至少有机会在他们不再需要它时停止它。

这里的技巧是使用闭包来确保您在间隔到期时仍然可以引用该对象(因此 self 变量)。

所以现在我可以做这样的事情:

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

关于Javascript:析构函数或类似的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22566667/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com