JavaScript namespace usage instructions

Source: Internet
Author: User

Speaking of the namespace, I think many of my friends know that php has a namespace and asp.net has a namespace. We will talk about the namespace of JavaScript. I will introduce it to you below.

When writing JavaScript in C or JAVA, people who are used to writing JavaScript may find that JavaScript does not have the namespace concept. Of course, if you have not been familiar with namespaces (such as writing JavaScript, PHP, python. This situation is common. Many people have written global variables directly when writing JavaScript, such:

The Code is as follows: Copy code

Function (){

}

Function B (){

}

What is a namespace? A type of code organization used by a language is classified by namespaces to differentiate different code functions. Regardless of the project size, if you do not strictly follow the namespace to write programs at the beginning, when you write tens of thousands of lines of JavaScript programs, I believe that you will regret that your object or function name is too messy. Therefore, we recommend that you develop a namespace habit at the beginning. For example, if you want to develop a project, the functions may be as follows:

 

You can name it as follows:

The Code is as follows: Copy code

// Configure
Var config = {};

// Front-end
Config. front = {};

// Background
Config. admin = {};

// Background data
Config. admin. data = {};

// Background module
Config. admin. module = {};

// Background color Module
Config. admin. module. color = {};

// Background image Module
Config. admin. module. images = {};

// Background search Module
Config. admin. module. search = {};



// Add the background color change function to the background color Module
Config. admin. module. color. changeBgColor = function (color ){
Document. body. style. background = color;
};

// This can be called
Config. admin. module. color. changeBgColor ('# f30 ');

Let's take a look at the structure of this object in the memory.

 

However, the above method of declaring a namespace does not seem intuitive. We use a more intuitive structured naming method:

The Code is as follows: Copy code
// Configure
Var config = {
// Front-end
Front :{},

// Background
Admin :{
// Data layer
Data :{},

// Module layer
Module :{
// Color Module
Color :{
// The background color change function
ChangeBgColor: function (color ){
Document. body. style. background = color;
},
// Foreground color change function
ChangeFnColor: function (color ){
Document. body. style. color = color;
}
},

// Image Module
Images :{

},

// Search Module
Search :{

}
}
}

};

// This can be called
Config. admin. module. color. changeBgColor ('# f30 ');

The above declaration method presents the structure well, and uses the namespace to conveniently manage and maintain the expansion program, when many developers write large numbers of JavaScript code, do not worry about naming conflicts. We can also write a namespace function to save the preceding complex declaration methods. For example, in the above example, I only use config temporarily. admin. module. color. for the changeBgColor function, I need to define config, admin, module, and color first. changeBgColor is complicated, so we can write a namespace registration function, which can be used directly after registration:

The Code is as follows: Copy code
// Namespace registration function
Var namespace = {
Reg: function (s ){
Var arr = s. split ('.');
Var namespace = window;

For (var I = 0, k = arr. length; I <k; I ++ ){
If (typeof namespace [arr [I] = 'undefined '){
Namespace [arr [I] = {};
}

Namespace = namespace [arr [I];
}
},
Del: function (s ){
Var arr = s. split ('.');
Var namespace = window;

For (var I = 0, k = arr. length; I <k; I ++ ){
If (typeof namespace [arr [I] = 'undefined '){
Return;
} Else if (k = I + 1 ){
Delete namespace [arr [I];
Return;
} Else {
Namespace = namespace [arr [I];
}
}
}
};

You can register a namespace in this way.

The Code is as follows: Copy code
// Register the namespace first
Namespace. reg ('config. admin. module. color ');

// Add function
Config. admin. module. color. changeBgColor = function (color ){
Document. body. style. background = color;
};

// Call the Function
Config. admin. module. color. changeBgColor ('# f30 ');


// Delete the namespace
Namespace. del ('config. admin. module. color ');

The namespace does not have a unique rule. Only the project owner and the project owner can analyze the program and give certain naming rules. For example, some projects are named based on the functional namespace and some projects are named based on the owner name. However, no matter which method is used, a reasonable namespace will not be reconstructed due to name conflicts when you cooperate with many people in large projects. Therefore, the js file in your site will include the namespace. js introduced first, which defines all namespaces and management for this project.

 

NamespaceObjectFactory: generate a NamespaceObject object based on fqn.
The NamespaceObjectFactory object has only one create method. The parameter is the namespace Name (Fully Qualified Name ). This method has a closure environment where a cache variable is used to cache all generated NamespaceObject objects.
A NamespaceObject object contains three attributes: stash (record the current namespace), fqn (namespace name), and proc (createProcedure object ). The methods include enqueue, call, valueof, merge, getStash, and getExport.

The Code is as follows: Copy code


74 var NamespaceObject = function _ Private_Class_Of_NamespaceObject (fqn ){
75 merge (this ,{
76 stash: {CURRENT_NAMESPACE: fqn },
77 fqn: fqn,
78 proc: createProcedure ()
79 });
80 };
81 merge (NamespaceObject. prototype ,{
82 enqueue: function (context ){
83 this. proc. next (context );
84 },
85 call: function (state, callback ){
86 this. proc. call (state, callback );
87 },
88 valueOf: function (){
89 return "# NamespaceObject <" + this. fqn + "> ";
90 },
91 merge: function (obj ){
92 merge (this. stash, obj );
93 return this;
94 },
95 getStash: function (){
96 return this. stash;
97 },
98 getExport: function (importName ){
99 if (importName = '*') return this. stash;
100
101 var importNames = importName. split (/,/),
102 retStash = {};
103 for (var I = 0, l = importNames. length; I <l; I ++ ){
104 retStash [importNames [I] = this. stash [importNames [I];
105}
106 return retStash;
107}
108 });
109 var NamespaceObjectFactory = (function (){
110 var cache = {};
111 return {
112 create: function (fqn ){
113 _ assertValidFQN (fqn );
114 return (cache [fqn] | (cache [fqn] = new NamespaceObject (fqn )));
115}
116 };
117 })();

Related Article

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.