A factory function is any function which is not a class or constructor that returns a (presumably new) object. In JavaScript, any function can return an object. When it does so without the new keyword, it’s a factory function.
Factory functions have always been attractive in JavaScript because they offer the ability to easily produce object instances without diving into the complexities of classes and the new keyword.
If you need to create many objects, you’ll want to combine the power of object literals and factory functions.
With a factory function, you can create as many user objects as you want.
If you’re building a chat app, for instance, you can have a user object representing the current user, and also a lot of other user objects representing all the other users who are currently signed in and chatting, so you can display their names and avatars, too .
by calling a factory method you avoid reallocating memory for each object you create, instead a factory method does that only once when it's called.
function Car(name, type) {
this.name = name;
this.type = type;
}
function Truck(name, type) {
this.name = name;
this.type = type;
}
function VehiclesFactoryMethod() {
this.create = function(name, type) {
switch(type) {
case "Car":
return new Car(name, type);
case "Truck":
return new Truck(name, type);
}
}
}
With our factory method in place, we are ready to use it for our object creation!
Let's instantiate our factory method object.
const VehiclesFactoryMethod = new VehiclesFactoryMethod();
const vehicles = [];
This array will simulate our Database for the purposes of this tutorial
Let's fill our array with some vehicles!
vehicles.push(VehiclesFactoryMethod.create("Nissan", "Car"));
vehicles.push(VehiclesFactoryMethod.create("MAN", "Truck"));
This function will output the inserted vehicles in a more stylized context
function print() {
console.log("Database of our vehicles : ");
console.log("Name: " + this.name);
console.log("Type: " + this.type);
}
vehicles.forEach( vehicle => {
print.call(vehicle);
});
Top comments (0)