Meaning closures

Closures in fact function to capture higher variable scope, functions, closures, no one function references, along with the closure will be destroyed.

function test() {
  var data = new Array(100000); var getData = function(){return data;}; setTimeout(getData, 10000); }

In general, local variables created within a function, after the function is run, it will be automatically destroyed. Example run every test function, it will create a data data, if there is no reference to the upper getData scope data variables , data at the end of the test run function, it will be destroyed. getData when it is created, it will subsequently create a special container for storing a reference to the role of the upper variable domain. So to speak, the closure getData function to create a reference to an external data capture variables. It stands to reason, getData variable function after the test run, it will also be destroyed. And so he did, if not behind the setTimeout words. Because setTimeout has been holding a reference to the getData function, and closure getData formed and captured data variable references, data and therefore the data will always exist and will not be destroyed immediately after the end of the test function. setTimeout will run after 10s getData function pointed to, then can release function reference, that is no longer a reference variable pointing to the getData function after 10s, then the closure getData form can also get destroyed, captured a top variables and it has been released. So example, getData closure is formed in the 10s after destruction.

So why is there a memory leak it?

Imagine if you are not using the example setInterval setTimeout but, then, getData function has been cited in the setInterval, the closures and closures getData formed captured variables will exist until you clearInterval. If you forget to clear, or you mistakenly played multiple timers know it is not only clear the last one, it had a memory leak.

In short, as long as no one will save the reference to the function, and this function and function closures formed also will be destroyed together.

 

Source: https: //segmentfault.com/q/1010000016554258/a-1020000016557945

Guess you like

Origin www.cnblogs.com/Alon-Td/p/12080575.html