In C and C#, namespaces are used to minimize name conflicts. For example, in the .NET Framework, namespaces help distinguish the Microsoft.Build.Task.Message class from System.Messaging.Message. JavaScript doesn't have any language-specific features to support namespaces, but it's easy to emulate namespaces using objects. If you are creating a JavaScript library, you can wrap them inside a namespace without defining global functions and classes, like this:
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 nested namespaces can be created:
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, library users can easily specify shorter aliases for namespaces:
// 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 used similar technology to implement namespaces. I will not explain it in detail here. Friends who need it can go to Du Niang to find it.
The above is the entire content of this article, I hope it will be helpful to everyone learning javascript