Referencing global variables in local scopes
I would like to know memory leak in the below mentioned code. Does Ja开发者_StackOverflow中文版vaScript do automatic garbage collection.
var aGlobalObject = SomeGlobalObject;
function myFunction() {
var localVar = aGlobalObject;
}
Do I have to clear the memory as given below.
var aGlobalObject = SomeGlobalObject;
function myFunction() {
var localVar = aGlobalObject;
localVar = null;// or delete localVar
}
Thanks
You don't have a memory leak in that code. The local variable references the same object as the global variable. When the function returns, the local variable is removed because nothing has a reference to it anymore. The object itself remains, because it's still referenced by the global variable. (When I say "the local variable is removed": Technically, the [implicit] container the variable is in no longer has anything referencing it and is available for garbage collection; the actual collection may happen later.)
Javascript does indeed have garbage collection. The delete
keyword means something totally different in Javascript than it does in, say, C++. Javascript objects have properties. You can completely remove a property from an object using delete
, e.g.:
var obj = {}; // Blank object
obj.foo = 5; // `obj` now has a property called `foo`
obj.foo = null; // `obj` STILL has a property called `foo`; its value is just null now
delete obj.foo; // `obj` no longer has a property called `foo`
Yes, JavaScript does garbage collection.
精彩评论