如何使用 jQuery/Javascript 从内存中删除对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16643156/
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-08-26 17:30:53  来源:igfitidea点击:

How to delete an object from memory using jQuery/Javascript?

javascriptjquery

提问by Rudresh Bhatt

I am creating an application in which I have a page for creating a customer. for that I have written following code.

我正在创建一个应用程序,其中有一个用于创建客户的页面。为此,我编写了以下代码。

customer=new MobileApp.CustomerViewModel(); //for creating new customer

I want to delete this object. how can I perform this ??

我想删除这个对象。我该如何执行此操作?

回答by taskinoor

Setting customer = nullwill make this enable for garbage collector, given that there is no other valid reference to that object.

customer = null鉴于没有对该对象的其他有效引用,设置将使垃圾收集器启用此功能。

回答by Prasath K

delete customer;

See about delete

查看关于删除

deleteoperator removes a property from an object. As customeris a property of the global object, not a variable, so it can be deleted

delete运算符从对象中删除属性。由于customer是全局对象的属性,而不是变量,所以可以删除

Note : customershould be a global one

注意:customer应该是全局的

customer=new MobileApp.CustomerViewModel();
delete customer; // Valid one

var customer1=new MobileApp.CustomerViewModel();
delete customer1; // Not a valid one

Sample Fiddle

样品小提琴

回答by Nagendra

Recursively destroy the object as shown below. Tested with chrome heap snapshot that the javascript objects are getting cleared in memory

递归销毁对象,如下所示。使用 chrome 堆快照测试,javascript 对象在内存中被清除

function destroy(obj) {
    for(var prop in obj){
        var property = obj[prop];
        if(property != null && typeof(property) == 'object') {
            destroy(property);
        }
        else {
            obj[prop] = null;
        }
    }
}