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.