Factory method
Create and return specific types of objects.
FunctionCreatecar (scolor, idoors, impg ){
VaROtempcar =NewObject ();
Otempcar. Color = scolor;
Otempcar. Doors = idoors;
Otempcar. mpg = impg;
Otempcar. showcolor =Function(){
Alert (This. Color );
}
Return otempcar;
}
Call example:
VaROcar1 = createcar ("red", 4,23 );
VaROcar2 = createcar ("blue", 3,25 );
Ocar1.showcolor ();
Ocar2.showcolor ();
Disadvantage: The method is already created. For example, in the preceding call example, both ocar1 and ocar2 have their own shocolor methods, but they can be shared.
Constructor Method
Example:
FunctionCar (scolor, idoors, impg ){
This. Color = scolor;
This. Door = idoors;
This. Mpg = impg;
This. Showcolor =Function(){
Alert (This. Color );
}
}
Call example:
VaROcar1 =NewCar ("red", 4, 23 );
VaROcar2 =NewCar ("blue", 3, 25 );
Disadvantage: Same as the factory method, the method is created again.
Prototype
This method uses the prototype attribute of the object to view it as the prototype on which the object is created. Here, we use an empty constructor to set the class name. Then, all attributes and methods are directly assigned to the prototype attribute, and the previous example is rewritten,CodeAs follows:
FunctionCar (){
}
Car. Prototype. color = "red ";
Car. Prototype. Doors = 4;
Car. Prototype. mpg = 23;
Car. Prototype. showcolor =Function(){
Alert (This. Color );
}
Call:
VaROcar1 =NewCar ();
VaROcar2 =NewCar ();
Disadvantage: The parameter initialization attribute value cannot be passed to the constructor.
Hybrid constructor/prototype
The constructor and prototype are used in combination. The example is as follows:
FunctionCar (scolor, idoors, impg ){
This. Color = scolor;
This. Door = idoors;
This. Mpg = impg;
}
Car. Prototype. showcolor =Function(){
Alert (This. Color );
}
Call example:
VaROcar1 =NewCar ("red", 4, 23 );
VaROcar2 =NewCar ("blue", 3, 25 );
Advantage: no memory waste, easy to create.
This is the main method adopted by ecmascript.
Dynamic Prototype Method
By using a hybrid constructor/prototype, the object method is defined outside the object, which makes people feel that it is not so object-oriented and is not visually encapsulated, therefore, a dynamic prototype method is generated:
function Car (scolor, idoors, impg) {
This . color = scolor;
This . door = idoors;
This . MPG = impg;
If ( typeof Car. _ initialized = "undefined") {
Car. prototype. showcolor = function () {
alert ( This . color);
};
Car. _ initialized = true ;< BR >}