【发布时间】:2012-01-16 22:51:53
【问题描述】:
所以我知道如何删除一个变量... variable = null;或删除变量;但是假设我有很多不同的变量都指向相同的值,但我只能访问其中的几个变量,我该如何清除该内存值。
那么举个例子……我有:
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.
我无法访问 x,因为它保存在我调用的函数中。这是因为它是一个巨大的闭包并运行异步 setTimeout 代码,因此它永远不会打开。
【问题讨论】:
-
我相当肯定
delete仅适用于对象属性。另外,内存管理通常留给垃圾收集器,你并没有那么高的控制度。 -
你可以删除一个变量,它只是设置它等于'undefined'。但是如果另一个变量指向内存中的相同值,则内存不会被删除。
-
不,您不能删除像
a、b或c这样的变量。你可以删除a.value,但那是因为它是一个对象属性。 (developer.mozilla.org/en/JavaScript/Reference/Operators/delete) -
对不起,我没有提到这是在全球范围内。所以是的,在函数中 delete 不适用于变量,但在全局中它可以。
标签: javascript pointers memory-leaks