Javascript does not natively support namespaces and requires workarounds.
When we create a JavaScript library, namespace is very important. We can encapsulate the scattered JavaScript files (*.js) that make up this JavaScript library in the namespace without defining global functions or classes. For example, Person, who appears many times in this chapter, can be encapsulated into a suitable namespace as part of the library:
Code 5-13:
var com = {};
com.anyjava = {};
com.anyjava.Person = function(name) {
//Private member
var _name = name;
//Accessor
this.getName = function() {
return _name;
};
this.setName = function(name) {
_name = name;
};
};
//Prototype
com.anyjava.Person.prototype = {
eat:function() {
alert(this.getName() " is eating something. ");
},
sleep:function() {
alert(this.getName() " is sleeping.");
},
walk:function() {
alert(this.getName() " is walking.");
}
};
var dirk = new com.anyjava.Person("Dirk");
dirk.eat() ;
From Code 5-13, we get a namespace that is more in line with the habits of Java developers, and when instantiating the Person object, we must also specify our command space path.
Here is a little tip. If you are using a JavaScript library developed by others and with a relatively complete namespace planning, you may be annoyed by writing lengthy namespaces every time. Bored. For example, if you are using the JavaScript library I developed, under the com.anyjava.control.ui namespace, there are many extended UI controls that you want to use. I guess you don’t want to write var xxx = new com many times. .anyjava.control.ui.XXX(). By specifying namespace aliases, we can write less repetitive code, as shown in Code 5-14, another method of instantiating Person in Code 5-13:
Code 5-14:
var ns = com.anyjava;
var dirk = new ns.Person("Dirk");
dirk.eat();
The last thing I will explain is, There is an issue you need to pay attention to when using namespaces. When writing a JavaScript library, in most cases namespace declaration statements may appear in multiple locations in a JavaScript file at the same time, or in multiple JavaScript files. However, a JavaScript language feature is that the last declared variable will overwrite the previously declared variable. Variables with the same name require us to pay attention to the issue of repeated declarations. That is to say, every time we declare a namespace object, it is recommended to first determine whether the namespace object already exists, as shown in Code 5-15:
Code 5-15:
if (typeof com.anyjava == "undefined") var com.anyjava = {};
This way we can ensure that the "com.anyjava" object is only declared once.