Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript namespacing convention

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?

like image 478
monsoon Avatar asked Jul 19 '13 15:07

monsoon


People also ask

Does JavaScript support namespace?

JavaScript does not provide namespace by default. However, we can replicate this functionality by making a global object which can contain all functions and variables.

What is global namespace in JS?

In JavaScript, it is nothing but a single global object which will contain all our functions, methods, variables and all that. Here ' MYAPPLICATION ' is acted as a JavaScript namespace and the only global object which contains all other items. JavaScript.

What is JavaScript namespace pollution?

Polluting Global namespace causes name collision. This name collision is very common in large projects where we may be using several javascript libraries. Let's discuss in detail what a name collision is. let's take a scenario in which 2 teams named A1 and A2 are working on a project.


1 Answers

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".

like image 171
bfavaretto Avatar answered Oct 23 '22 01:10

bfavaretto