用于调试内存泄漏问题,我想知道函数闭包是否会像任何全局变量一样保存在内存中?
function() {
var blah;
return function() {
}
}
答案 0 :(得分:1)
如果你的意思是内在功能,那就不会。当没有对函数对象的引用时,它将被丢弃。
function() A {
var blah = //someobject;
return function() {
}
}
var x = A();
//inner function and blah created
x = null;
//inner function (and the variable blah) can now be garbage collected
答案 1 :(得分:0)
闭包就像垃圾收集类一样 - 也就是说,为每个创建的闭包分配了封闭变量:
function foo () {
var x = 0;
return function(){return x}
}
var a = foo(); // memory allocated for x
var b = foo(); // memory allocated for second instance of x
/* This is what I mean by it behaves like a class: returning the
* inner function creates a new closure much like calling a class
* with `new` creates a new object
*/
a = null; // memory for x will be de-allocated in the next round
// of garbage collection
b = null; // memory for second x will be de-allocated eventually
function bar () {
y = foo()
}
bar(); // memory for third instance of x is allocated when foo()
// is called inside bar().
// memory for third instance of x will be de-allocated eventually
// after bar() returns because y has already been de-allocated