JavaScript object-oriented namespace _js object-oriented

Source: Internet
Author: User
In small projects for JavaScript use, just write a few function on the line. But in large projects, especially in the development of the pursuit of a good user experience of the site, such as SNS, will use a lot of javascrpt, sometimes the workload of JavaScript than C #, then write a bunch of function, it will appear very messy, messy, even the naming conflict, Management and maintenance are all very troublesome. In this case, we need to use object-oriented thinking to develop JavaScript. So let's just drop it:

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 code as follows:

Declares a global object registernamespace function, which is a full path to the namespace, such as "Cnblogs.blog"
registernamespace = function (fullName) {
Cut namespaces 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];
To create a statement that constructs a Namespace object, if it does not exist, in turn
Streval + = "If" (typeof ("+ Strns +") = = ' undefined ') "+ strns +" = new Object (); "
}
if (Streval!= "") eval (streval);
}

OK, now to register a few namespaces to try, blog Park For example, blog Park has several modules "blog", "News", "group" ...
Copy Code code as follows:

Registernamespace ("Cnblogs.blog");
Registernamespace ("Cnblogs.news");
Registernamespace ("Cnblogs.group");

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