Turn from: http://www.rainleaves.com/html/1684.html
A JavaScript static class is simply a class that does not have to be created by new, and can be used directly, like the built-in global class of JavaScript, such as math and object.
JavaScript Static class notation
var myClass = {
name: "Rain Dozen Duckweed",
value: "http://www.rainleaves.com",
run:function () {
alert ("Run");
}
}
This makes it possible to implement a basic JavaScript static class, but it doesn't make much sense to define a few variables.
Let's switch to JavaScript. Static class notation
var MyClass = (function () {
var _name = "Rain Dozen duckweed";
var _value = "http://www.rainleaves.com";
var privatevalue = "Rainleaves";
var main = function () {
alert (this.name);
alert (_name);
MyMethod ();
};
var myMethod = function () {
alert (privatevalue);
}
return{
Name:_name,
value:_value,
main:main
}
}) ();
In this way, a class is returned by the form (function () {return{}}) (), the closure, and assigned to MyClass. This allows you to create a private environment by closing the package to protect
Privatevalue, such as private properties, can be more structured code.
In this code, _name,_value is assigned to Mymethod.name and Mymethod.value by reference, while the main method is also exposed as a public property, and Privatevalue and MyMethod are always private methods, hidden within the closure.
Run
Myclass.main ();
Operation Result: Print two times rain dozen duckweed, once rainleaves
myclass.name = "Rain dozen duckweed rainleaves";
Myclass.main ();
Operation Result: The Rain dozen duckweed rainleaves, rain dozen duckweed, rainleaves
In practice, we use JavaScript static classes to separate the logic of each page in different classes, not interfere with each other, but also in the most of these classes defined to a total static class, the implementation of code block, clear structure. Such as:
var Manage = {};
Manage.myclass = (function () {return{}}) ();
Manage.myclass2 = (function () {return{}}) ();
...