1

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?

Greg Gum
  • 33,478
  • 39
  • 162
  • 233
  • In your simple example: No. Read up on [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures) they are very useful/essential at times. Also [IIFE](http://en.wikipedia.org/wiki/Immediately-invoked_function_expression) – Xotic750 Feb 06 '14 at 01:21

2 Answers2

3

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(){ … })()”?

Community
  • 1
  • 1
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • Good points Brad, would you argue that declaring in a function is likely unnecessary if a module is namespaced? – pedalpete Feb 06 '14 at 01:24
  • 1
    @pedalpete: i tend to do it regardless. However, you could run in to issue with not necessarily functions within the "`MyApp`" object, but helper functions that you don't want cluttering the global namespace. – Brad Christie Feb 06 '14 at 01:26
  • On point two of your answer, don't they both keep further declarations out of the global scope? I don't see the difference as far as scoping is concerned. – Greg Gum Feb 06 '14 at 01:50
0

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.

pedalpete
  • 21,076
  • 45
  • 128
  • 239