Generally, the most common syntax format of JavaScript code is to define function xxx () {/* code... */}. Many such functions are often defined. Function names are prone to conflicts, especially when multiple js files are introduced. Therefore, it is necessary to introduce namespaces.
Javascript itself does not have a namespace concept and needs to be simulated by an object.
For example, define a namespace class for creating a namespace:
Function NameSpace (){}
This is a constructor, but it does not do anything. Let's use the following Code related to the comment:
Var comment = new NameSpace ();
Comment. list = function () {/* code */};
Comment. counter = 0;
The first row creates the so-called namespace (actually a blank object), named comment, and the second and third rows define the two methods in the space. You can use comment. list () or comment. counter ++ for calling;
Create a sub-namespace:
Comment. add = new NameSpace ();
Comment. add. post = function () {/* code */}
Comment. add. check = function (){}
The namespace concept is introduced to avoid the same function name. The above process can also be defined as follows:
Var comment = {
List: function () {/* code */},
Add :{
Post: function () {/* code */},
Check: function () {/* code */}
}
}
Prototype. this method is widely used in js. Although this method is more intuitive like a tree, as long as there are a little more nodes, the eyes are busy looking for the relationship between these nodes, the namespace method is to horizontally describe the relationship tree. The hierarchical relationship is represented literally. The two methods have the same effect, but their writing style has their own characteristics.