javascript simulates the namespace

  • 2020-05-30 19:24:31
  • OfStack

In C++ and C#, namespaces are used to minimize name collisions. For example, in.NET Framework, the namespace helps to distinguish the class Microsoft.Build.Task.Message from the class System.Messaging.Message. JavaScript doesn't have any language-specific capabilities to support namespaces, but it's easy to use objects to simulate namespaces. If you want to create an JavaScript library, you can wrap them in a namespace without having to define 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 " );

One level of a namespace may not be one-only, 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 in these verbose 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 Microsoft AJAX library, you will find that the author of the library USES a similar technique to implement the namespace.

That's the end of this article. I hope it will be helpful for you to learn javascript


Related articles: