I have a JS function which gets called on the page every few seconds. It's an AJAX update thing.
Being a function, I declare local variables. I don't want to use closures or global variables for various reasons.
I'd never considered this, but do I need to release/clear the variables at the end of the function to release memory or will开发者_StackOverflow JS do this for me automatically?
Generally, no. Variables declared with var
are local and are garbage collected when you return. If you omit the var
then the variables are global, and using the delete
keyword may be useful for global variables in some instances, but generally it's good practice to declare all variables with var
anyway to not pollute the window
namespace.
delete
can be useful when using prototype-based inheritence though, e.g:
function myclass() {
this.variable = 'myvalue'
...
delete this.variable // finished with this variable
}
var inst = new myclass()
Bear in mind that if inst
is deleted or becomes out of scope (garbage collected) all the attributes in it will be deleted as well. delete
can also be useful for deleting items from hash tables:
var d = {}
d['blah'] = 'myvalue'
...
delete d['blah']
There are some browser-specific garbage collection bugs. IE sometimes has problems cleaning attributes in DOM elements and closures etc for example, though many of these problems have been reduced in IE8 I believe.
Javascript has automatic garbage collection. You don't need to deallocate anything.
Variables are released once they are out of scope, in your case, the local variables that are declared inside your function will be automatically freed by js garbage collector, you don't have to worry about them.
精彩评论