There is no concept of namespace in JavaScript, but to reflect the object-oriented idea,
should have a namespace, just like package in java and namespace in .net.
is mainly used to prevent class name conflicts. The same class name will not conflict as long as it belongs to different namespaces.
The simplest way to create a namespace:
var java = {};
java.util = {};
//This creates the namespace successfully: java.util
//We can add classes (functions) and attributes under java.util , or object
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 creation and naming Space method:
//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 use arguments to receive, arguments are similar to arrays,
If multiple parameters are passed in, they will be saved in order, the value method: arguments[0],arguments[1]....*/
var a = arguments ,o = null,d,rt;
for(var i = 0; i < a.length; i )
{
d = a[i].split('.'); / / Split the incoming parameters with the '.' symbol and put them into the 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
Statement: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