extracrispy
extracrispy

Reputation: 679

Javascript: How to destroy the value a group of variables point to?

So I know how to delete one variable... variable = null; or delete variable; but say I have lots of different variables that all point to the same value but I can only access a few of those variables, how can I clear that value of memory.

So how bout an example... I have:

var a = {value:5};    //create the reference everything points to
var b = a;
var c = a;

CallFunctionThatKeepsReference(a);
//var x = a;          //x in this function but I can't directly access x.

a = null; b = null; c = null;    //the object still exists in x.
delete a; delete b; delete c;    //the object still exists in x.

//What can I do to accomplish this effect...
Nuke(a);  //or b, or c
//a,b,c,x now all point to null.

I can't access x because it is kept in a function that I call. This is because it is a giant closure and runs async setTimeout code so it never uncloses.

Upvotes: 2

Views: 182

Answers (1)

ziesemer
ziesemer

Reputation: 28697

I'd strongly recommend another approach at this. JavaScript isn't C, so you don't need to absolutely and explicitly reclaim all of your own memory. Instead, write your code so that it works well with the garbage collector. Specifically, ensure that your variables are declared within functions / closures, at the lowest-level possible for what you need to accomplish. Once the function finishes, any variables and memory will automatically be recycled.

Upvotes: 4

Related Questions