The easiest way to create namespaces:
Copy Code code as follows:
var java = {};
Java.util = {};
This creates a successful namespace: 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 results: Java.util.HashMap
Encapsulates how namespaces are created:
Define an object, JS uses {} curly braces to define objects, equivalent to var jsobject = new Object ();
Copy Code code as follows:
var jsobject = {};
Jsobject.namespace = function ()////////////////////Jsobject
{
/* The following code arguments the arguments passed into the function, and when the function does not explicitly define the parameter,
function can also pass in parameters and receive them with arguments, arguments like arrays,
If more than one argument is passed in, the value is saved in order: arguments[0],arguments[1]....*/
var a = Arguments,o = Null,d,rt;
for (var i = 0; i < a.length; i++)
{
D = a[i].split ('. '); The incoming arguments are segmented with the symbol '. ' and put into the D array.
RT = D[0];
Determines whether the first value in the array is undefined and, if not defined, is defined as an empty object {} and assigned to the variable O
Eval (' if (typeof ' + rt + ' = ' = ' undefined ') {'
+ rt + ' = {};} o = ' + rt + ';
for (var j = 1; j < D.length; J + +)
{
/* Loop traversal array d each value as key, add to Object o, if the key exists in O, then take the o median, if
Does not exist, the assignment is an empty object {} * *
O[D[J]] = o[d[j]] | | {};
o = O[d[j]];
}
}
}
Jsobject.namespace ("Org.myjs"); DECLARE namespaces: ORG.MYJS
Org.myJs.Student = function ()//-Define class under namespace Org.myjs Student
{
Defines a variable in the class student and assigns an initial value, but the access rights for this variable are public
This.studentno = ' s001 ';
This.studentname = ' xiaoming ';
This.sex = ' Male ';
}
var s = new org.myJs.Student (); To create an object of the student class
Alert (' School No.: ' +s.studentno);
Alert (' Name: ' +s.studentname);
Alert (' Sex: ' +s.sex);
Effects and first (i) JavaScript experience summary object-oriented-class results like