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);
What is a Constructor in C++? A constructor in C++ is a special 'MEMBER FUNCTION' having the same name as that of its class which is used to initialize some valid values to the data members of an object. It is executed automatically whenever an object of a class is created.
Namespace declarations appear only at global scope. Namespace declarations can be nested within another namespace. Namespace declarations don't have access specifiers (Public or Private). No need to give a semicolon after the closing brace of the definition of namespace.
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.
This is generally a good idea; additionally, if your objects require a set of shared functions that should not be exposed you can wrap them all inside a closure, like a module:
var shapes = (function() {
// private variables
var foo = 0;
// private function
function get_area(w, h)
{
return w * h;
}
return {
Rectangle: function(w, h) {
this.width = w;
this.height = h;
// call private function to determine area (contrived example)
this.area = get_area(w, h);
}
}
}());
var s = new shapes.Rectangle(100, 5);
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