In Javascript, what’s the difference between a namespace and a closure? They seem very similar to me.
EDIT
Specifically, this article discusses namespaces and closures, and has sentences like
Now, we’re still going to have situations where we’ll want to declare
variables that don’t naturally fit into a namespaced object
structure. But we don’t want those variables to have a global scope. This is where
self-invoking functions come in.
It goes on to give what looks a lot like a closure, as an “object namespace”. It looks to me like the namespace IS a closure…but maybe it’s not…? Help?
A namespace is essentially an
Objectwith no interesting properties that you shove stuff into so you don’t have a bunch of variables with similar and/or conflicting names running around your scope. So, for example, something likeA closure is when a function ‘retains’ the values of variables that are not defined in it, even though those variables have gone out of scope. Take the following:
If I let
c = makeCounter()and then repeatedly callc(), I’ll get0, 1, 2, 3, .... This is because the scope of the inner anonymous function thatmakeCounterdefines ‘closes’ overx, so it has a reference to it even thoughxis out of scope.Notably, if I then do
d = makeCounter(),d()will start counting from 0. This is becausecanddget different instances ofx.