Creating namespaces with self-invoking functions

When a project’s javascript grows, it can be easy to lose ourselves, buried under thousands of lines of js code. That’s why I like to create namespaces to keep everything together.

Let’s say I have functions to work with cats and I create a namespace for it because there are lots of other functions related to dogs.

As you see, to access the cat list I must use the complete name including the namespaces like this : Animal.Cat.list. You can guess that it will get pretty long as the code grows.

Let’s make this call shorter.

Now, I only have to write c.list because c is an alias of the Animal.Cat namespace. Thanks to self-invocation!

You probably noticed that the code is longer but this is just an example. In a real situation, this technique would make your code much clearer.

Don’t forget to subscribe to my newsletter!

  • http://www.javascriptkata.com/2011/08/22/self-invoking-functions-explained-line-by-line/ Self-invoking functions explained line by line » Javascript Kata

    [...] See my post about using self-invoking functions to create namespaces. [...]

  • Freakezoid D

    Uncaught SyntaxError: Unexpected token ;
    And you can’t write c.list…..

  • Freakezoid D

    you also need to write Animal.Cat.list

  • http://www.javascriptkata.com dsimard

    there was an error in my gist, it is now corrected.

  • http://www.javascriptkata.com dsimard

    If you mean that we have to call Animal.Cat.list to access it outside the class, it’s what it’s supposed to be!

  • Guest
  • http://www.javascriptkata.com dsimard

    My post has nothing to do with OO, it’s just names that I use because I think they are funny.

    I have to say that I read this post a two weeks ago and I don’t even agree. So I’ll continue the use of cats and dogs.

  • http://claimid.com/strager strager

    In case someone suggests it:

    Don’t use `this` to solve this problem.

  • http://www.outsource-website-development.com outsourcing web development

    I can set up my new idea from this post. It gives in depth information. Thanks for this valuable information for all. And of course nice review about the application. 

  • http://kalzdjsdcvi.com/ dYcxcgcvf

    2011…

    Thank you, I’ve recently been looking for info about this topic for ages and yours is the best I’ve discovered till now. But, what about the bottom line? Are you sure about the source?…