javaScript factory way primitive way
Because the properties of an object can be dynamically defined after the object is created, code similar to the following was written when JavaScript was first introduced.
Copy the code code as follows:
var oCar = new Object;
oCar.color = "blue";
oCar.doors = 4;
oCar.mpg = 25;
oCar.showColor = function() {
alert(this.color);
};
In the above code, the object car is created. Then give it a few attributes: It's blue, has four doors, and gets 25 miles per gallon. The last attribute is actually a pointer to a function, meaning the attribute is a method. After executing this code, the object car can be used. But there is a problem here, that is, you may need to create multiple instances of car, which is obviously not a good way.
Solution: Factory methods
To solve this problem, developers created factory functions that create and return objects of a specific type. For example, the function createCar() can be used to encapsulate the previously listed operations of creating a car object:
Copy the code code 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;
}
var oCar1 = createCar("red",4,23);
var oCar2 = createCar("blue",3,25);
oCar1.showColor(); //Output "red"
oCar2.showColor(); //Output "blue"
Calling this factory function will create a new object and give it all necessary attributes. Add parameters to the createCar() function to assign values to the color, doors and mpg attributes of the car object to be created. This makes two objects have the same properties, but different property values. The bad thing about this method is that every time a car object is created (that is, the createCar function is called once), the showColor method is repeatedly created for each object. This is not necessary. In fact, each object shares the same function. . So we try to declare its method attributes outside the function.
Define object methods outside factory functions
Some developers avoid this problem by defining the object's method outside the factory function and then pointing to the method through a property:
Copy the code code as follows:
function showColor() {
alert(this.color);
}
function createCar(sColor,iDoors,iMpg) {
var oTempCar = new Object;
oTempCar.color = sColor;
oTempCar.doors = iDoors;
oTempCar.mpg = iMpg;
oTempCar.showColor = showColor;
return oTempCar;
}
var oCar1 = createCar("red",4,23);
var oCar2 = createCar("blue",3,25);
oCar1.showColor(); //Output "red"
oCar2.showColor(); //Output "blue"
In the above rewritten code, the function showColor() is defined before the function createCar(). Inside createCar(), the object is given a pointer to the existing showColor() function. Functionally, this solves the problem of repeatedly creating function objects; but semantically, the function does not look like a method of the object.