Javascript does not natively support namespaces and requires workarounds.
When we create a JavaScript library, the namespace plays an important role. We can encapsulate the scattered JavaScript files (*.js) that make up the 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:
Copy the code code as follows:
var com = {};
com.anyjava = {};
com.anyjava.Person = function(name) {
//Private members
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 Java developers' habits, 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 get tired of writing lengthy namespaces every time. 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:
Copy the code code as follows:
var ns = com.anyjava;
var dirk = new ns.Person("Dirk");
dirk.eat();
The last thing I will explain is an issue that needs to be paid 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:
Copy the code code as follows:
if (typeof com.anyjava == "undefined") var com.anyjava = {};
In this way we can ensure that the "com.anyjava" object is only declared once.