Method 1: factory method --- create and return the factory function of a specific type of object)
Function createCar (color, doors, mpg ){
Var tempCar = new Object;
TempCar. color = color;
TempCar. doors = doors;
TempCar. mpg = mpg;
TempCar. showCar = function (){
Alert (this. color + "" + this. doors );
}
Return tempCar;
}
Method 2: constructor method --- constructor looks like a factory function
Function Car (color, doors, mpg ){
This. color = color;
This. doors = doors;
This. mpg = mpg;
This. showCar = function (){
Alert (this. color );
};
}
Method 3: prototype: The prototype attribute of an object is used to create a prototype on which the object depends.
Function Car (color, doors, mpg ){
This. color = color;
This. doors = doors;
This. mpg = mpg;
This. drivers = new Array ("nomad", "angel ");
}
Car. prototype. showCar3 = function (){
Alert (this. color );
};
Method 4: Mixed constructor/prototype --- use constructor to define all non-function attributes of an object, and use prototype to define function attributes (methods) of an object)
Function Car (sColor, iDoors, iMpg ){
This. color = sColor;
This. doors = iDoors;
This. mpg = iMpg;
This. drivers = new Array ("Mike", "Sue ");
}
Car. prototype. showColor = function (){
Alert (this. color );
};
Method 5: The Dynamic Prototype Method defines non-function attributes in the constructor, while the function attributes are defined using the prototype attributes. The only difference is that the location of the object method is assigned.
Function Car (sColor, iDoors, iMpg ){
This. color = sColor;
This. doors = iDoors;
This. mpg = iMpg;
This. drivers = new Array ("Mike", "Sue ");
If (typeof Car. _ initialized = "undefined "){
Car. prototype. showColor = function (){
Alert (this. color );
};
Car. _ initialized = true;
}
}
// This method uses the sign (_ initialized) to determine whether any method has been granted to the prototype.
Use prototype. Function Bar (text, url ){
This. text = text;
This. url = url;
}
Bar. prototype = {
Render: function (){
Document. write ('<a href = "' + this. url + '">' + this. text + '</a> ');
}
}