How to introduce namespaces through JavaScript programming _ javascript skills
Source: Internet
Author: User
JavaScript programming introduces namespace Methods JavaScript code is generally the most common syntax format is to define function xxx () {/* code... */}, there are often a lot of such function definitions. 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.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service