Namespace your JavaScript

There are a couple of ways to create namespaces for your code.  This format allows you to intentionally expose functions as public or keep them internal/private.  I like the following version…

 

var mynamespace = new function () {

var internalFunction = function() {
     //TODO: code
};

this.publicFunction = function() {
    //TODO: code
};

};

To execute the above public function from the global namespace would be done like mynamespace.publicFunction();  Obviously, you can use smaller/shorter names to make it easier to type.

Simple, now why the heck do this?

  • A namespace is a container and allows you to bundle up all your functionality using a unique name
  • In JavaScript a namespace is really just an object that you have attached all further methods, properties and objects
  • Without the usage of namespaces every function will be in the global (aka window) namespace (this occurs by default if you do not use a namespace).  It is a good practice not to clutter the global namespace
  • Using namespaces prevents the overwriting of existing function names
  • Using namespaces is one step in the direction of object-oriented which promotes modularity and code re-use

Author

David

comments powered by Disqus

Categories

Recent Tweets

@jeffrey_doucet @Brian_Bancroft Canadians, self define themselves as NOT American, rather than being Proud Canadians
Retweeted by @dyardy Why do so many Canadians obsess over American policy that won’t impact us while being fairly ambivalent to day-to-d… twitter.com/i/web/status/9…
@melrobbins I was looking for 50$ earlier today, and still can't find it...ideas :)
Trump Watches Up To 8 Hours Of TV Per Day | HuffPost #SmartNews ===that explains everything huffingtonpost.com/entry/trump-te…
Retweeted by @dyardy Boston https://t.co/QmtMIF8P0F