View Single Post
Old 02-01-2013, 06:13 PM   PM User | #3
Airblader
Regular Coder

 
Join Date: Jan 2013
Location: Germany
Posts: 374
Thanks: 3
Thanked 44 Times in 44 Posts
Airblader can only hope to improve
Yes, both snippets are essentially the same. The second one simply declares an object, the first one is a little bit trickier: It defines a function that returns an object and then immediately calls itself (so-called self-invoking function).
You're also right about the purpose: Except for the namespace (i.e. the name of your module) nothing will be global, which means that you don't break other code and just as important, other code won't break yours (unless it is loaded after yours and explictly overwrites your namespace object).

The only thing to look out for now is to ensure that namespaces won't collide. This is already fairly unlikely and even if it happens, it's an easy fix. In other languages like Java, for example, it's common practice to use reverse domain notation as the "namespace" (technically it's more a subpackage structure, but the idea is the same). The Google Play Store even uses this as the unique identification for an app!

The tricky thing about this in JavaScript is a concept called closures. A simple example:

Code:
var counter = (function () { 
    var current = 0; 
    return function () {
        console.log( current++ );
    };
})();

counter(); // 0
counter(); // 1
counter(); // 2

console.log( current ); // undefined

var current = 42;

counter(); // 3
counter(); // 4

console.log( current ); // 42
The variable current sort of acts like a private variable: It is within the closure of the self-invoked function and will stay alive in there, so the returned function can keep using it. However, it will be completely unknown to the global scope. Even adding a global variable with the same name will not interfere with this.
Airblader is offline   Reply With Quote