7

wI'm unsure which is the better namespace convention to use.

var App = {}; // global variable, the root of our namespace
(function() {

   App.something = function() {

   }

})();

or

(function() {

   window.App = {}; //global variable, the root of our namespace

   App.something = function() {

   }

})();

window.App and var App are both global variables so both conventions achieve the same outcome, but which is better?

monsoon
  • 97
  • 5

1 Answers1

3

The only difference is that in the first variant, App cannot be deleted from window, although it's accessible as a property of the global object. In the second case, delete window.App works. Also, note that you should be attaching your namespace to window, not Window, as JavaScript is case-sensitive, and Window is a constructor.

Other than that, both are basically the same, there is no "better".

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • The uppercase on window was a mistake, but thanks for letting me know anyway. Would you say one convention is used more commonly in the js community than the other? – monsoon Jul 19 '13 at 15:39
  • 2
    I'm not sure, but the second looks cleaner to me. Another common one is `var App = (function(){ /* return your object from here */ }())` – bfavaretto Jul 19 '13 at 15:42