JavaScript 局部变量的内存释放 [英] Memory release from local variable in JavaScript
问题描述
我有一个 JS 函数,每隔几秒就会在页面上调用一次.这是一个 AJAX 更新的事情.
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.
我从来没有考虑过这个,但是我需要在函数末尾释放/清除变量来释放内存还是 JS 会自动为我做这个?
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 JS do this for me automatically?
推荐答案
一般来说,没有.用 var
声明的变量是本地的,返回时会被垃圾回收.如果省略 var
则变量是全局变量,在某些情况下使用 delete
关键字可能对全局变量有用,但通常用var
无论如何都不会污染 window
命名空间.
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
在使用基于原型的继承时很有用,例如:
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()
请记住,如果 inst
被删除或超出范围(垃圾收集),其中的所有属性也将被删除.delete
也可用于从哈希表中删除项目:
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']
存在一些特定于浏览器的垃圾收集错误.例如,IE 有时会在清理 DOM 元素和闭包等中的属性时遇到问题,尽管我相信在 IE8 中这些问题中的许多已经减少了.
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 局部变量的内存释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!