The most common syntax format for JavaScript code is to define functions function xxx(){/*code...*/}. There are often a lot of function definitions like this. Function names are prone to conflicts, especially when multiple js files are introduced. The conflict is particularly obvious. Therefore, it is necessary to introduce namespaces.
Javascript itself has no concept of namespace and needs to be simulated with objects.
For example, define a namespace class for creating a namespace:
function NameSpace(){
}
This is a constructor, but it does nothing , and then the following code related to comments:
var comment = new NameSpace();
comment.list = function(){/*code...*/};
comment.counter = 0;
The first line creates a so-called namespace (actually a blank object) named comment, and the second and third lines define two methods in this space. You can use comment.list() or comment.counter when calling;
Create a sub-namespace:
comment.add = new NameSpace();
comment.add.post = function( ){/*code...*/}
comment.add.check = function(){}
The reason why the concept of namespace is introduced is to avoid the problem of the same function name. The above process can also be defined like this:
var comment = {
list : function(){/*code...*/},
add : {
post : function( ){/*code...*/},
check : function(){/*code...*/}
}
}
There are a lot of them in prototype.js Using this method, although this method is more intuitive like a tree, as long as there are slightly more nodes, the eyes are busy looking for the relationships between these nodes. The namespace approach is to describe this relationship tree horizontally, and the hierarchical relationship is directly expressed. Literally, the two methods have the same effect, but their writing styles have their own characteristics.
Extend one more method:
NameSpace.prototype.appendChild = function(ns){
for (var key in ns){
this[key] = ns[key ];
}
return this;
}
NameSpace.prototype.copyChild = NameSpace.prototype.appendChild;