Greg Gum
Greg Gum

Reputation: 37875

Declaring Namespaces

Consider:

var MyApp = MyApp || {};
MyApp.doAlert = function(message) { alert(message); };
MyApp.doAlert("from MyApp");

and

(function(ns) {
    ns.doAlert = function(message) {
    alert(message);
};
})(window.MyApp2 = window.MyApp2 || {});
MyApp2.doAlert("from MyApp2");

They both work, and as far as I can tell, are essentially the same. The purpose being to declare a namespace.

Is there a benefit to one style over the other?

Upvotes: 1

Views: 42

Answers (2)

pedalpete
pedalpete

Reputation: 21536

The first one is a standard declaration of your MyApp namespace.

The second one, you're declaring your MyApp2 namespace and in the same process, you're passing it into a self-declaring anonymous function.

There is nothing wrong with this, but it isn't exactly conventional. The first way is more common, readable, and for that reason, probably better. Unless you have a good reason for declaring your methods within a function, which I can't see the benefit of.

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101594

The latter is wrapping the method(s) in an anonymous function, likely for two reasons:

  1. Shorter (abbreviated) reference to the same thing (MyApp vs ns).
  2. It's wrapped in an anonymous function to keep any further declarations out of global scope.

Usually you see the latter more often as to avoid multiple modules defining common variable names (and overriding meaning).

See also What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

Upvotes: 3

Related Questions