JavaScript 局部变量的内存释放
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2681511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Memory release from local variable in JavaScript
提问by Bob
I have a JS function which gets called on the page every few seconds. It's an AJAX update thing.
我有一个 JS 函数,每隔几秒就会在页面上调用一次。这是一个 AJAX 更新的事情。
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 JS do this for me automatically?
我从未考虑过这一点,但是我是否需要在函数末尾释放/清除变量以释放内存,还是 JS 会自动为我执行此操作?
回答by cryo
Generally, no. Variables declared with varare local and are garbage collected when you return. If you omit the varthen the variables are global, and using the deletekeyword may be useful for global variables in some instances, but generally it's good practice to declare all variables with varanyway to not pollute the windownamespace.
一般来说,没有。用 with 声明的变量var是本地的,返回时会被垃圾回收。如果省略,var则变量是全局delete变量,在某些情况下,使用关键字可能对全局变量有用,但通常最好声明所有变量,var以免污染window命名空间。
deletecan be useful when using prototype-based inheritence though, e.g:
delete但是,在使用基于原型的继承时可能很有用,例如:
function myclass() {
this.variable = 'myvalue'
...
delete this.variable // finished with this variable
}
var inst = new myclass()
Bear in mind that if instis deleted or becomes out of scope (garbage collected) all the attributes in it will be deleted as well. deletecan also be useful for deleting items from hash tables:
请记住,如果inst被删除或超出范围(垃圾收集),其中的所有属性也将被删除。delete也可用于从哈希表中删除项目:
var d = {}
d['blah'] = 'myvalue'
...
delete d['blah']
There are somebrowser-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.
有一些特定于浏览器的垃圾收集错误。例如,IE 有时会在清理 DOM 元素和闭包等中的属性时遇到问题,尽管我相信在 IE8 中这些问题中的许多已经减少了。
回答by Max Shawabkeh
Javascript has automatic garbage collection. You don't need to deallocate anything.
Javascript 具有自动垃圾收集功能。你不需要释放任何东西。
回答by Mahesh Velaga
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.
变量一旦超出范围就会被释放,在你的情况下,在你的函数中声明的局部变量将被 js 垃圾收集器自动释放,你不必担心它们。

