Home > Web Front-end > JS Tutorial > JavaScript object-oriented namespace_js object-oriented

JavaScript object-oriented namespace_js object-oriented

WBOY
Release: 2016-05-16 18:28:15
Original
787 people have browsed it

For the use of JavaScript in small projects, just write a few functions. However, in large-scale projects, especially in the development of websites that pursue good user experience, such as SNS, a large amount of JavaScript will be used. Sometimes the workload of JavaScript exceeds that of C#. In this case, writing a bunch of functions will seem It is very messy, disorganized, and may even have naming conflicts. It is very troublesome to manage and maintain. In this case we need to use object-oriented thinking to develop JavaScript. Then let’s leave it like this:

For a project, you must first have a namespace. So the first thing we have to do is define a function to register the namespace. The code is as follows:

Copy code The code is as follows:

// Declare a global object RegisterNameSpace function, The parameter is the full path of the namespace, such as "cnblogs.blog"
RegisterNameSpace = function(fullName) {
// Split the namespace into N parts
var nsArray = fullName.split('.');
var strEval = "";
var strNS = "";
for (var i = 0; i < nsArray.length; i ) {
if (i != 0){
strNS = ".";
}
strNS = nsArray[i];
// Create statements to construct the namespace object (if it does not exist) in sequence
strEval = "if (typeof (" strNS ") == 'undefined') " strNS " = new Object();"
}
if (strEval != "") eval(strEval);
}

Okay, now let’s try registering a few namespaces. Let’s take the Blog Park as an example. The Blog Park has several modules: “Blog”, “News”, “Group”...
Copy code The code is as follows:

RegisterNameSpace("cnblogs.blog");
RegisterNameSpace( "cnblogs.news");
RegisterNameSpace("cnblogs.group");

In fact, the namespace here is an object, an Object.
Author: cnblogs Uncle Xiang
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