I have read that creating a namespace for JavaScript projects helps to reduce conflicts with other libraries. I have some code with a lot of different types of objects for which I have defined constructor functions. Is it good practice to put these inside the namespace as well?
For example:
var shapes = {
Rectangle: function(w, h) {
this.width = w;
this.height = h;
}
};
which can be called via:
var square = new shapes.Rectangle(10,10);
This namespacing is called the “Singleton pattern” and it’s one of the main patterns reccomended by the famous “Gang of Four” design patterns book.
From the great (and free) book Learning JavaScript Design Patterns:
So yes, it’s a well used concept in many programming languages and a great for preventing global namespace object collisions in JavaScript.
See also: Simplest/Cleanest way to implement singleton in JavaScript?