This article describes how to implement the namespace effect in javascript. For more information, see Javascript native and namespace.
When we create a JavaScript library, the namespace becomes very important. We can combine the scattered JavaScript files in this JavaScript Library (*. js) is encapsulated in a namespace without defining global functions or classes. For example, the Person that appears multiple times in this chapter can be encapsulated into a proper namespace as part of the Library:
Code 5-13:
The Code is as follows:
Var com = {};
Com. anyjava = {};
Com. anyjava. Person = function (name ){
// Private member
Var _ name = name;
// Accessors
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 fits the habits of Java developers. when instantiating the Person object, we also need to specify the path of our command space.
Here is a tip. If you are using a JavaScript library developed by someone else with a relatively complete namespace plan, you may get bored with writing lengthy namespaces every time. For example, if you are using the JavaScript library I developed. anyjava. control. in the ui namespace, there are many extended UI controls you want to use. I guess you do not want to write var xxx = new com many times. anyjava. control. ui. XXX (). By specifying the namespace alias, we can write less duplicate Code, as shown in Code 5-14, another method for instantiating Person in Code 5-13:
Code 5-14:
The Code is as follows:
Var ns = com. anyjava;
Var dirk = new ns. Person ("Dirk ");
Dirk. eat ();
Finally, I want to explain one of the issues that need attention when using namespaces. When writing a JavaScript library, the namespace declaration statement may appear in multiple locations of a JavaScript file at the same time, or in multiple JavaScript files, however, the JavaScript language features that the final declared variables will overwrite the same name variables declared on the front. This requires us to pay attention to the issue of repeated declarations, that is, every time a namespace object is declared, we recommend that you first determine whether the namespace object already exists, as shown in Code 5-15:
Code 5-15:
The Code is as follows:
If (typeof com. anyjava = "undefined") var com. anyjava = {};
In this way, we can ensure that the "com. anyjava" object is declared only once.