4

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 ??

Rudresh Bhatt
  • 1,935
  • 2
  • 23
  • 29
  • delete variableName ; – Akshay Deep Giri May 20 '13 at 05:34
  • 2
    Note that JavaScript's `delete` keyword is NOT for deleting contents from memory, it is only for removing properties from within an object. [Read the docs](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete). Note that `delete x;` Will attempt to delete a property `x` that exists in the global namespace object. – ajp15243 May 20 '13 at 05:37
  • is it a global variable or a local one – Arun P Johny May 20 '13 at 05:37

3 Answers3

17

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

taskinoor
  • 45,586
  • 12
  • 116
  • 142
3
delete customer;

See about delete

delete operator removes a property from an object. As customer is a property of the global object, not a variable, so it can be deleted

Note : customer should be a global one

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

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

Sample Fiddle

Prasath K
  • 4,950
  • 7
  • 23
  • 35
  • This doesn't answer the question, and delete doesn't affect memory: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete – tog22 Oct 18 '21 at 20:35
3

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

function destroy(obj) {
    for(var prop in obj){
        var property = obj[prop];
        if(property != null && typeof(property) == 'object') {
            destroy(property);
        }
        else {
            obj[prop] = null;
        }
    }
}
DBS
  • 9,110
  • 4
  • 35
  • 53
Nagendra
  • 106
  • 2