I see in the code or sometimes people talk about it, for some JavaScript code:
(function() {
var something;
function someFunction() {
// some code here
}
// do something
}());
That's an "Immediately Invoked Function Expression", or IIFE. I often hear people say, "yeah, do it in a closure", or "do this in a closure" in the code comment -- as if a closure is "protecting the leak to the global space."
But is that the correct concept? I think it is a local scope, or an anonymous local scope, that is shield any local variables from leaking to the global scope. It really has nothing to do with a closure, which is a function with a scope chain. Sure, the anonymous function used for the IIFE is a closure, but it is not relevant here. If you say you want a closure, it is because you want the access to the current scope (and all scopes in scope chain). To say, shielding local variable to the global scope "by using a closure", is not a correct concept, is it?
Update: In any language that doesn't have closure, such as C, you can still do the exact same thing of shielding any local variables to leak into the global space. So it is not "closure" that is doing the job.
something
". Normally the "// do something" would be "return object with some getters and/or setters forsomething
", so that code outside the IIFE can only access or manipulatesomething
using exactly the methods returned by the IIFE and nothing else.