The simplest way to create a namespace:
var java = { };
java.util = {};
//This creates the namespace successfully: 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
// Encapsulate the method of creating a namespace:
//Define an object. Use {} braces to define the object in js, which is equivalent to var JsObject = new Object();
var JsObject = {};
JsObject.namespace = function() //Define a function namespace under the JsObject object
{
/*In the following code, arguments are the parameters passed in by the function. When the function does not clearly define parameters,
function can also pass in parameters and receive them with arguments. Arguments are similar to arrays,
If multiple parameters are passed in, they will be saved in order. The value method is: arguments[0], arguments[1]....*/
var a = arguments,o = null,d,rt;
for(var i = 0; i < a.length; i )
{
d = a[i].split('.'); //Use the incoming parameters with the symbol '.' Split and put into d array.
rt = d[0];
//Determine whether the first value in the array is undefined. If it is undefined, define it as an empty object {} and assign it to the variable o
eval(' if (typeof ' rt ' == "undefined"){'
rt ' = {};} o = ' rt ';');
for(var j = 1; j < d.length; j )
{
/*Loop through each value of array d as a key and add it to object o. If key exists in o, take the middle value of o. If
does not exist, assign the value as 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 under the namespace org.myJs Student
{
//Define a variable in class Student and assign it an initial value, but the access permission of this variable is public
this.studentNo = 's001';
this.studentName = 'Xiao Ming ';
this.sex = 'Male';
}
var s = new org.myJs.Student(); //Create an object of Student class
alert('Student number: ' s .studentNo);
alert('Name:' s.studentName);
alert('Gender:' s.sex);
Effects and the first article (1) javascript Experience summary object-oriented - class results are the same