Javascript to simulate namespace _ javascript skills

Source: Internet
Author: User
JavaScript does not support namespaces in any specific language, but it is easy to use objects to simulate namespaces. We will discuss this issue today and hope you will like it. In C ++ and C #, namespaces are used to minimize name conflicts. For example, in. NET Framework, the namespace helps distinguish Microsoft. Build. Task. Message from System. Messaging. Message. JavaScript does not support namespaces in any specific language, but it is easy to use objects to simulate namespaces. To create a JavaScript library, you can wrap them in the namespace without defining global functions and classes, as shown below:

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

A level of a namespace may not be unique, so you can create a nested namespace:

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 exhausting. Fortunately, the library user can easily specify a shorter alias for the namespace:

// MSDNMagNS.Examples and Pet definition...// think “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 uses similar technologies to implement the namespace, which is not described in detail here, if you need a friend, go to Duniang.

The above is all the content in this article. I hope it will be helpful for you to learn javascript.

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.