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

时间:2014-03-21 18:23:35

标签: javascript

我创造了这个小对象,它在间隔方面非常方便,并且作为一个动画帧非常好用,但它有这个小东西。如果对实例的引用丢失,则间隔将继续。

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方法,但我不确定我是否可以从内部销毁实例物体。这很有意义,但是......任何帮助都表示赞赏!

1 个答案:

答案 0 :(得分:1)

做这样的事情怎么样:

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