【发布时间】:2016-11-17 09:42:02
【问题描述】:
我一直在阅读有关 js 最佳实践和常见错误的信息,我从https://www.toptal.com/javascript/10-most-common-javascript-mistakes 看到了这段代码
var theThing = null;
var replaceThing = function () {
var priorThing = theThing; // hold on to the prior thing
var unused = function () {
// 'unused' is the only place where 'priorThing' is referenced,
// but 'unused' never gets invoked
if (priorThing) {
console.log("hi");
}
};
theThing = {
longStr: new Array(1000000).join('*'), // create a 1MB object
someMethod: function () {
console.log(someMessage);
}
};
};
我尝试将此代码输入控制台并多次调用replaceThing(),确实如此,即使在 GC 之后,Chrome 任务管理器中的内存使用量也会上升。
闭包unused 保留对priorThing 的引用,从而使其不符合GC 条件。但是:
-
priorThing = theThing执行时,unused闭包中的引用是否也更改为theThing? - 即使 #1 不是这种情况,当
replaceThing的执行完成时,变量unused是否应该超出范围?
【问题讨论】:
标签: javascript memory-leaks garbage-collection