var theThing = null;
var replaceThing = function () {
var originalThing = theThing;
var unused = function () {
if (originalThing)
console.log("hi");
};
theThing = {
longStr: new Array(1000000).join('*'),
someMethod: function () {
console.log(someMessage);
}
};
};
setInterval(replaceThing, 1000);
Question 1: The function declares the context when it is created, and updates the local variables in the scope chain when executed. The scope chain includes local variables inside the function when executed. What is more confusing is that the unused function is not When executing, how do you know that the unused function will definitely reference originalThing?
Question 2: How to explain this memory leak? I hope the experts can explain it in more detail?
Question 1: After the variables in the function (replaceThing) leave its scope, if the function (replaceThing) is used once and is not referenced again until the program is executed, it will be recycled after a while.
Question 2: If you look at the thing assignment action, the action of creating an array is being done all the time. 1,000,000 join operations are performed at a time, and they are continuously executed. The speed of memory recycling cannot keep up with its growth rate, which will soon lead to memory leaks.