javascript 删除类的实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17243463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:36:13  来源:igfitidea点击:

Delete instance of a class?

javascript

提问by Vitaliy Isikov

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

Then I initialize it like var x = new T();

然后我像这样初始化它 var x = new T();

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.

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

回答by Denys Séguret

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

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

This means you must know the variables holding those references.

这意味着您必须知道保存这些引用的变量。

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

如果你只是将它分配给变量x,你可以这样做

x = null;

or

或者

x = undefined;

or

或者

delete window.x;

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

但是最后一个,正如 Ian 所指出的,只有在您将 x 定义为 的显式属性时才能工作window

回答by KingRider

Classnot same function are different. Not work a delete. Classis system modification.

不一样,功能不一样。不工作删除。是系统修改。

class SAFunc {
  method1(){
    console.log("1");
  }
  method2(){
    console.log("2");
  }
}
let func  = new SAFunc();
func['method2']()

Try:

尝试:

  • delete window['func']-- not work
  • delete eval['func']-- not work
  • delete window['SAFunc']-- not work
  • ...
  • ...
  • delete window['func']- 不行
  • delete eval['func']- 不行
  • delete window['SAFunc']- 不行
  • ...
  • ...


Function- command work delete

功能- 命令工作删除

method1 = function(){
  console.log("func1");
}
function method2() {
  console.log("func2");
}
var SAFunc = { method3: function() { console.log("func3"); } }

Make ur test... Try:

让你的测试...尝试:

  • delete window['method1']
  • delete window['method2']
  • delete SAFunc['method3']
  • delete window['method1']
  • delete window['method2']
  • delete SAFunc['method3']

Good fun! i love programming

好开心!我喜欢编程

Enjoin us ;)

吩咐我们;)