-
-
Save thunklife/9532333 to your computer and use it in GitHub Desktop.
| (function IIFE(){ | |
| function init(){ | |
| var something = "cool", | |
| somethingElse = [1,2,3,4,5,6,7,8], | |
| $btn1 = $("btn1"), | |
| $btn2 = $("btn2"), | |
| $btn3 = $("btn3"); | |
| $btn1.click(function hander(evt){ | |
| console.log("1", something); | |
| }); | |
| $btn1.click(function hander(evt){ | |
| console.log(3, something); | |
| }); | |
| $btn1.click(function hander(evt){ | |
| console.log(3.14, something); | |
| }); | |
| } | |
| }()); |
They technically/academically close over the entire scope, not just individual variables. The fact that they don't seem to lexically reference somethingElse is potentially, implementation-dependent, something the engines might be able to optimize for, where they wouldn't keep somethingElse around prevented from GC. But that's not guaranteed, and there are many cases where even the modern browsers struggle with these sorts of things, so sometimes it's optimized and other times not.
So I teach the strict narrow interpretation, ignoring implementation details, as it's safer to code defensively than to code assuming certain optimizations that are beyond your control.
Also, consider if there was a with, eval, or Function (or even, ugly, a setTimeout(..) or setInterval(..) with a string param for the "code") present in one of those inner functions. It would be impossible for the engine to know if it needed to close over somethingElse or not, so it would have to pessimistically assume that it should.
Also, an explicit block-scoping could even further help tell the engine "don't keep somethingElse around for the inner functions":
(function IIFE(){
function init(){
var something = "cool",
$btn1 = $("btn1"),
$btn2 = $("btn2"),
$btn3 = $("btn3");
{
let somethingElse = [1,2,3,4,5,6,7,8];
// ...
}
$btn1.click(function hander(evt){
console.log("1", something);
});
$btn1.click(function hander(evt){
console.log(3, something);
});
$btn1.click(function hander(evt){
console.log(3.14, something);
});
}
}());@getify - Thanks for the response! I think I get what you mean now. So this would be an issue even if the function didn't use the value of something, because it's still in scope, correct?
Makes perfect sense. Thanks.
Cheers! :)
I'm not sure I understand the concept of closure bloat. I understand that each anonymous function has access to all of
init's variables, but my understanding is that they only close oversomething. So how does the scope of the other variables create bloat in the anonymous function?