Among the several javascript class definition methods, the most common method is the combination of prototypeconstructor and dynamic prototype. There are several methods to build a class in Javascript:
1. Factory method
The Code is as follows:
Function createCar (){
Var car = new Object ();
Car. color = "B ";
Car. length = 1;
Car. run = function () {alert ("run ");}
Return car;
}
After defining such a function, you can use:
Var car1 = createCar ();
Var car2 = createCar ();
Create a new object. The problem with this method is that every time a car object is created, the run Function must be re-created. This wastes memory.
2. Constructor Mode
The Code is as follows:
Function Car (){
This. color = "B ";
This. length = 1;
This. run = function () {alert ("run ");}
}
Var car1 = new Car ();
Var car2 = new Car ();
This is the most basic method, but there are also problems with the factory Method
3. prototype Method
The Code is as follows:
Function Car (){
}
Car. prototype. color = "B ";
Car. prototype. length = 1;
Car. prototype. run = function () {alert ("run ");
}
The disadvantage of this method is that when this class has a reference attribute, changing this attribute of an object also changes the attributes of other objects.
For example:
The Code is as follows:
Car. prototype. data1 = new Array ();
Var car1 = new Car ();
Var car2 = new Car ();
Car1.data1. push ("");
In this case, car2.data also contains the "a" element.
4. Prototype/Constructor Mixing Mode[Common]
The Code is as follows:
Function Car (){
This. color = "B ";
This. length = 1;
This. data1 = new Array ();
}
Car. prototype. run = function (){
Alert ("dddd ");
}
This method removes the disadvantages. It is currently widely used.
5. Dynamic prototype [common]
The Code is as follows:
Function Car (){
This. color = "B ";
This. length = 1;
This. data1 = new Array ();
If (typeof Car. initilize = "undefined "){
Car. prototype. run = function () {alert ("");}
}
Car. initilize = true;
}
Among these methods, the most common method is the combination of prototype/constructor and dynamic prototype.