First, the simplest one is:
Copy codeThe Code is as follows: // The following lines of code demonstrate the namespace, class, and function simulation definition and usage:
NameSpace = {};
NameSpace. Class = function (){
This. Method = function (info) {alert (info );}
};
New NameSpace. Class (). Method ("Hello world ");
Some more visible code in various situations
1. Simulation of Classes
Copy codeThe Code is as follows: // class definition
Function Class (info ){
// Private member
Var privateData = "private data ";
Var privateMethod = function () {writeline ("private ");};
Function privateMethod2 (info) {writeline ("private ");}
// Public Member (use this)
This. Data = "public data ";
This. Method = function () {writeline (info );};
};
// Static member of the class
Class. StaticData = "static data ";
Class. StaticMethod = function (info) {writeline (info );};
2. namespace Simulation
Copy codeThe Code is as follows: function NameSpace (){}
Or
NameSpace = {};
Or
NameSpace = new Object ();
3. Goal: to create a class instance and call the instance method
Copy codeThe Code is as follows: var o = new NameSpace. Class ("hello world ");
O. Method ();
// Use existing class definitions and use static methods to mount them to the NameSpace
NameSpace. Class1 = Class;
New NameSpace. Class1 ("new NameSpace. Class1 (). Method ()"). Method ();
// Or: Create a class definition
NameSpace. Class2 = function (info ){
This. Method = function () {writeline (info );};
};
New NameSpace. Class2 ("new NameSpace. Class2 (). Method ()"). Method ();
4. Objective: To Call static functions of a class
Copy codeThe Code is as follows: NameSpace. Class. StaticMethod ();
// Static object + static method
NameSpace. Class3 ={}; // {} indicates that this is an object, or use new object ();
NameSpace. Class3.Method = function (info) {writeline (info );};
NameSpace. Class3.Method ("NameSpace. Class3.Method ()");
// Or: assign a new object to a static member.
NameSpace. Class4 = new Class ("NameSpace. Class4.Method ()");
NameSpace. Class4.Method ();
// Or: anonymous functions are used to define classes, and new objects are used to create objects.
NameSpace. Class5 = new (function (info ){
This. Method = function () {writeline (info );};
}) ("NameSpace. Class5.Method ()");
NameSpace. Class5.Method ();
// Or: JSON (class definition + creation completed at the same time)
// The advantage is that the parameter cannot be passed in.
NameSpace. Class6 = {
Method: function (info) {writeline (info );}
};
NameSpace. Class6.Method ("NameSpace. Class6.Method ()");
DEMO code:<Br/> Javascript class and namespace simulation <p> <B> check the source code and perform a test </B> </p> <p> collection: <I> http://surfsky.cnblogs.com </I> </p> <p> last updated: <I> 2010-10 </I> </p> <p>