Reputation: 37875
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
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
Reputation: 101594
The latter is wrapping the method(s) in an anonymous function, likely for two reasons:
MyApp
vs ns
).Usually you see the latter more often as to avoid multiple modules defining common variable names (and overriding meaning).
Upvotes: 3