删除一个类的实例? [英] Delete instance of a class?

查看:89
本文介绍了删除一个类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样创建的类:

I have a class that was created like this:

function T() {
    this.run = function() {
        if (typeof this.i === 'undefined')
            this.i = 0;
        if (this.i > 10) {
            // Destroy this instance
        }
        else {
            var t = this;
            this.i++;
            setTimeout( function() {
                t.run();
            }, 1000);
        }
    }
}

然后我将其初始化为 var x = new T();

我不知道如果从内部破坏此实例一次如果达到10次迭代。

I'm not sure how to destroy this instance from within itself once if reaches 10 iterations.

此外,我不知道如何在外部销毁它,以防我想在它达到10之前停止它。

Also, I'm not sure how to destroy it externally either, in case I want to stop it before it reaches 10.

推荐答案

要删除实例,请在JavaScript中删除指向它的所有引用,以便垃圾收集器可以回收它。

To delete an instance, in JavaScript, you remove all references pointing to it, so that the garbage collector can reclaim it.

这意味着你必须知道持有这些引用的变量。

This means you must know the variables holding those references.

如果你刚将它分配给变量 x ,你可能会这样做

If you just assigned it to the variable x, you may do

x = null;

x = undefined;

delete window.x;

但最后一个,由Ian精确定制,只有在将x定义为显式属性时才能工作窗口

but the last one, as precised by Ian, can only work if you defined x as an explicit property of window.

这篇关于删除一个类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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