Home > Web Front-end > JS Tutorial > JavaScript simulates namespace_javascript tips

JavaScript simulates namespace_javascript tips

WBOY
Release: 2016-05-16 16:03:30
Original
1212 people have browsed it

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”);
Copy after login

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”);
Copy after login

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);
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template