如何彻底销毁JavaScript对象? [英] How to completely destroy a JavaScript object?

查看:111
本文介绍了如何彻底销毁JavaScript对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node.js开发一个游戏服务器,我想在队列中存储匹配项,以便能够在一定的超时后销毁它们。这基本上是我的实现:

I am developing a game server with node.js, and I would want to store matchs inside a queue, in order to be able to destroy them after a certain timeout. Here is basically my implementation :

var matchs = [];

var createMatch = function () {
    matchs.unshift(new Match());
    matchs[0].start();

    setTimeout(function () {
        delete matchs[matchs.length - 1];
        matchs.pop();
    }, 5 * 1000);
};

function Match() {

    // ...

    this.foo = 0;

    this.start = function () {
        var self = this;

        setInterval(function () {
            console.log(self.foo++);
        }, 1 * 1000);
    };
}

当我打电话给<$ c $时,这段代码应该做什么c> createMatch(),每秒显示一个递增的数字,并在5秒后停止。但是,如果我运行此代码,它将继续永久显示数字,这使我认为我的匹配对象没有被正确销毁。

What this code is supposed to do is, when I call createMatch(), display an increasing number every second, and stop after 5 seconds. However if I run this code, it will continue displaying numbers forever, which leads me to think that my Match objects are not destroyed properly.

请帮助吗?

推荐答案

delete 运算符会删除一个属性,但不会销毁对象,也不会销毁任何对象对象已创建(如间隔)。所以你的 setTimeout 实际上可能是:

The delete operator deletes a property but does not destroy an object nor any thing the object has created (like the interval). So your setTimeout could actually be:

setTimeout(function () {
    matchs.pop().destroy();
}, 5 * 1000);

pop 从数组中删除元素(不再引用并且可以清除)但是 destroy()需要显式告诉匹配对象它需要清理的东西。在Javascript中,当对象真正从内存中删除时,无法执行某些操作。没有这样的概念。

The pop removes the element from the array (no longer referenced and can be cleaned) but the destroy() is needed to to explicitly tell the Match object it needs to clean things up. In Javascript there is no way to do something when the object is really deleted from memory. There is no such concept.

所以你的匹配对象负责跟踪事后需要清理的东西如下例所示:

So your Match object is responsible for keeping track of things it needs to clean afterwards like the example bellow:

    function Match() {
    this.intervalId = undefined;

    this.start = function () {
        ...
        this.intervalId = setInterval(function () {
            ...
        }, 1 * 1000);
    };

    this.destroy = function() {
        if (intervalId)  {
            clearInterval(this.intervalId);
        }
    }
}

超时和间隔为<可以通过适当的函数销毁的em> resource 。在这种情况下 clearInterval()

Timeouts and intervals are a resource that can be destroyed by the appropriate functions. In this case clearInterval().

这篇关于如何彻底销毁JavaScript对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆