JavaScript Simulation namespace _javascript tips

Source: Internet
Author: User

In C + + and C #, namespaces are used to minimize name collisions as much as possible. For example, in the. NET Framework, namespaces help distinguish the Microsoft.Build.Task.Message class from the System.Messaging.Message. JavaScript does not have any language-specific features to support namespaces, but it is easy to use objects to simulate namespaces. If you want to create a JavaScript library, you can wrap them in a namespace without having to define global functions and classes, as follows:

var msdnmagns = {};
Msdnmagns.pet = function (name) {//code here};
MSDNMagNS.Pet.prototype.toString = function () {//code};
var pet = new Msdnmagns.pet ("Yammer");

One level of the namespace may not be unique, so you can create nested namespaces:

var msdnmagns = {};
Nested namespace "Examples"
msdnmagns.examples = {};
MSDNMagNS.Examples.Pet = function (name) {//code};
MSDNMagNS.Examples.Pet.prototype.toString = function () {//code};
var pet = new MSDNMagNS.Examples.Pet ("Yammer");

As you can imagine, typing these lengthy nested namespaces can be tiring. Fortunately, the library user can easily specify a shorter alias for the namespace:

Msdnmagns.examples and Pet definition ...
"Using Eg = Msdnmagns.examples;"
var Eg = msdnmagns.examples;
var pet = new Eg.pet ("Yammer");
Alert (PET);

If you look at the source code of the Microsoft AJAX Library, you will find that the author of the library used a similar technology to implement the namespace, there is no detailed instructions, the need for the small partners to find their own Niang.

The above is the entire content of this article, I hope to learn JavaScript can help you

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.