JavaScript factory method is the original method
Because the properties of an object can be dynamically defined after the object is created, when JavaScript was first introduced, code similar to the following would be written
In the above code, create the object car. 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 Method
To solve this problem, developers created factory functions that create and return objects of specific types. For example, the function createCar() can be used to encapsulate the previously listed operations of creating a car object:
var oCar1 = createCar("red",4,23);
var oCar2 = createCar("blue",3,25);
oCar1.showColor(); //Output "red"
oCar2.showColor(); //Output "blue"
Call this factory function to create a new object and give it all necessary attributes. By adding parameters to the createCar() function, you can 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.
Defining object methods outside the factory function
Some developers define object methods outside the factory function, and then point to the method through attributes to avoid this problem:
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.