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?
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.
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.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With