Write the project need to put JS package processing, otherwise very messy. Then think of the front-end big God Ruan a peak, to blog search for a while really have harvest
Reference article:
Three ways JavaScript defines classes (Class) JavaScript Object-oriented programming (i): encapsulation
The minimalist approach is used here:
How to define a class:
This method defines a generator as well as a constructor (similar to the Factory mode bar)
var Cat = {
Createnew:function () {
var cat = {};
Cat.name = "Mao";
Cat.makesound = function () {alert ("Meow Meow");};
return cat;
}
};
Cat is the generator class, CreateNew is a constructor function, Cat is an entity object, Cat.name is a member variable
How to call the constructor:
var cat1 =// meow Meow
How to define a private variable:
Cat.name is a public variable that can be accessed directly by the external
The method of defining a private variable is to define a local variable in the constructor so that only the member function of the class can access the variable, and the external access is undefined
var Cat =function() { var cat = {}; var sound = "Meow meow"function() {alert (sound);};
var privatefun () {alert ("Private")}
Cat.publicfun () {
Privatefun (); Note that there is no use of this.privatefun ();
Alert ("Public");
}
return Cat; }};
Test results
var test =// undefined// "Private" " public"
How to define static variables (data sharing):
Define the variables within the cat construction class: This involves the knowledge of closures, the cat class has only one strength, and cat1=cat.createnew (), is actually a child function in the cat class to define a variable, the child function can access the parent class/parent function within the variable, so no matter the entity class modifies the Cat's member variables , the variables in the cat class have been modified to achieve the equivalent of Java static variables.
var Cat ="Meow meow"function() { var cat =function function (x) {cat.sound = x;}; return cat; }};
So sound is a static variable
Then generate two instance objects and use one of them to modify the sound
var cat1 = cat.createnew (); var cat2 =// meow meow cat2.changesound ("La la la"// la la la
Cat2.changesound ("La la La");
Cat1.makesound (); La La la
JavaScript Object-Oriented programming