The simplest way to create a namespace is:
Copy codeThe Code is as follows: var java = {};
Java. util = {};
// The namespace is successfully created: java. util
// We can add classes (functions), attributes, or objects under java. util.
Java. util. HashMap = function ()
{
This. ShowMessage = function ()
{
Alert ("java. util. HashMap ");
}
}
Var map = new java. util. HashMap ();
Alert (map. ShowMessage (); // display result: java. util. HashMap
// Encapsulate the method for creating a namespace:
// Define an Object. The Object is defined in braces {} in js, equivalent to var JsObject = new Object ();Copy codeThe Code is as follows: var JsObject = {};
JsObject. namespace = function () // define a function namespace under the JsObject object
{
/* In the following code, arguments is the parameter passed in by the function. When the function does not explicitly define the parameter,
Function can also input parameters and use arguments to receive them. arguments is similar to an array,
If multiple parameters are input, they are saved in order. Valid values: arguments [0], arguments [1]... */
Var a = arguments, o = null, d, rt;
For (var I = 0; I <a. length; I ++)
{
D = a [I]. split ('.'); // splits the passed parameters with the symbol '.' and puts them in the d array.
Rt = d [0];
// Determine whether the first value in the array is undefined. If not, it is defined as an empty object {} and assigned to variable o
Eval ('If (typeof '+ rt +' = "undefined "){'
+ Rt + '={};} o =' + rt + ';');
For (var j = 1; j <d. length; j ++)
{
/* Cyclically traverse array d. Each value is used as the key and added to object o. If the key exists in o, the o value is used.
If no value exists, the value is assigned to an empty object {}*/
O [d [j] = o [d [j] || {};
O = o [d [j];
}
}
}
JsObject. namespace ("org. myJs"); // declare the namespace: org. myJs
Org. myJs. Student = function () // define the class Student under the namespace org. myJs
{
// Define the variables in the class Student and grant the initial value, but the access permission for this variable is public
This. studentNo = 's001 ';
This. studentName = 'xiaoming ';
This. sex = 'male ';
}
Var s = new org. myJs. Student (); // create a Student Class Object
Alert ('student ID: '+ s. studentNo );
Alert ('name: '+ s. studentName );
Alert ('gender: '+ s. sex );
The effect is the same as that of article 1 (1) javascript Experience Summary object-oriented-class results