Factory method
Create and return specific types of objects.
Copy codeThe Code is as follows:
Function createCar (sColor, iDoors, iMpg ){
Var oTempCar = new Object ();
OTempCar. color = sColor;
OTempCar. doors = iDoors;
OTempCar. mpg = iMpg;
OTempCar. showColor = function (){
Alert (this. color );
}
Return oTempCar;
}
Call example:
Copy codeThe Code is as follows:
Var oCar1 = createCar ("red", 4,23 );
Var oCar2 = 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:
Copy codeThe Code is as follows:
Function Car (sColor, iDoors, iMpg ){
This. color = sColor;
This. door = iDoors;
This. mpg = iMpg;
This. showColor = function (){
Alert (this. color );
}
}
Call example:
Copy codeThe Code is as follows:
Var oCar1 = new Car ("red", 4,23 );
Var oCar2 = new Car ("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, and then all the attributes and methods are directly assigned to the prototype attribute. Rewrite the previous example. The Code is as follows:
Copy codeThe Code is as follows:
Function Car (){
}
Car. prototype. color = "red ";
Car. prototype. doors = 4;
Car. prototype. mpg = 23;
Car. prototype. showColor = function (){
Alert (this. color );
}
Call:
Copy codeThe Code is as follows:
Var oCar1 = new Car ();
Var oCar2 = new Car ();
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:
Copy codeThe Code is as follows:
Function Car (sColor, iDoors, iMpg ){
This. color = sColor;
This. door = iDoors;
This. mpg = iMpg;
}
Car. prototype. showColor = function (){
Alert (this. color );
}
Call example:
Copy codeThe Code is as follows:
Var oCar1 = new Car ("red", 4,23 );
Var oCar2 = new Car ("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:
Copy codeThe Code is as follows:
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;
}
}
Author: Artwl
Source: http://artwl.cnblogs.com