Home > Web Front-end > JS Tutorial > body text

How to introduce namespaces in JavaScript programming_javascript skills

WBOY
Release: 2016-05-16 19:11:50
Original
986 people have browsed it

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...*/}
}
}

prototype.js There are a lot of them 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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!