If you assign a value to a variable in javascript without first declaring that variable with var
, it goes into the global scope.
So if, within a module, I do something like this:
var MyModule = function() {
var _public = {};
var doSomething = function() {
alert("foo");
};
doSomethingElse = function() {
alert("bar");
};
_public.init = function(options) {
_public.options = options;
}
return _public;
} ();
Then the following things are true:
_public
lives inside the scope ofMyModule
._public.init
is insidepublic
, so it’s withinMyModule
, and I can callMyModule.init()
to invoke it.doSomething
is a private function inMyModule
.doSomethingElse
is a function in the global scope.
We want to minimize the amount of junk that’s in the global scope, lest we run into some very confusing bugs resulting from naming collisions.
And this has been today’s Fun with Javascript.