Factory method Create and return objects of specific types.
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:
var oCar1=createCar("red",4,23);
var oCar2=createCar("blue", 3,25);
oCar1.showColor();
oCar2.showColor();
Disadvantages: Methods are created repeatedly. As in the above calling example, both oCar1 and oCar2 have their own shoColor method, but this can be shared.
Constructor method
Example:
function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.door=iDoors;
this.mpg=iMpg ;
this.showColor=function(){
alert(this.color);
}
}
Call example:
var oCar1=new Car("red",4,23);
var oCar2 =new Car("blue",3,25);
Disadvantages: Like the factory method, the method is created repeatedly.
Prototype method This method uses the prototype property of the object, which can be regarded as the prototype on which creating new objects depends. Here, an empty constructor is used to set the class name, and then all properties and methods are directly assigned to the prototype attribute. Rewriting the previous example, the 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:
var oCar1=new Car();
var oCar2=new Car();
Disadvantages: The value of the property cannot be initialized by passing parameters to the constructor
Mixed The constructor/prototype method Use the constructor and prototype method together, the example is as follows:
function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.door=iDoors;
this. mpg=iMpg;
}
Car.prototype.showColor=function(){
alert(this.color);
}
Calling example:
var oCar1=new Car("red",4, 23);
var oCar2=new Car("blue",3,25);
Advantages: No memory waste, easy to create.
This method is the main method used by ECMAScript.
Dynamic prototype method Using a mixed constructor/prototype method to define the object's method outside the object, which makes people feel not so object-oriented and not in Visually good encapsulation, so the dynamic prototype method is produced:
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