3 ms·
Using closures to encapsulate private variables is a good idea, but the way this article recommends doing it doesn't demonstrate any of the benefit as it doesn'
by kylec 14y ago
Using closures to encapsulate private variables is a good idea, but the way this article recommends doing it doesn't demonstrate any of the benefit as it doesn't really close over anything. I don't know if it's an example of good JS code, but something like the basic closure definition of a counter might have better demonstrated the ability to hide state:
var counter = (function () {
var i = 0;
return function () {
i += 1;
return i;
}
}());
Where the internal variable, i, is inaccessible to anything but the counter function itself.
- jblotus 14y agoauthor here, it wasn't about hiding private variables. i was demonstrating using closures to avoid global namespace collisions which i think is generally a big problem for beginners.
- catshirt 14y agoi believe you mean using functions, not closures. your post doesn't seem to have the same misnomer, and simply explains lexical function scope. it doesn't seem to touch on the closure, while your parent comment does.
- jblotus 14y agowell, functions close over scope no matter what you call them.
- catshirt 14y agonot exactly. closures close over scope. functions alone simply create a new scope. these concepts are not synonymous. if your function doesn't return another function, the references from that function are deallocated once the function has executed. when your function returns a function (a "closure"), the inner function closes over the variables of the outer function, maintaining references to it's context as long as you maintain a reference to the closure.
- jblotus 14y agook i see your point. i conflated the terms function and closure in this case.