Factory Function in JavaScript

In JavaScript, factory functions provide an alternative way to create objects and are commonly used as a pattern for object creation. A factory function is a function that returns an object when invoked. It encapsulates the object creation process and allows for customization and configuration of the created objects. Here's an explanation of factory functions with an example:
function createPerson(name, age) {
// Create a new object
const person = {};
// Set properties
person.name = name;
person.age = age;
// Define methods
person.sayHello = function() {
console.log(`Hello, my name is ${this.name}.`);
};
person.getAge = function() {
return this.age;
};
// Return the object
return person;
}
// Create instances using the factory function
const john = createPerson("John", 30);
const jane = createPerson("Jane", 25);
// Access properties and call methods
console.log(john.name); // Output: John
john.sayHello(); // Output: Hello, my name is John.
console.log(jane.getAge()); // Output: 25
In this example, we have a createPerson factory function that accepts name and age as parameters.
Inside the function:
We create an empty
personobject using an empty object literal ({}).We set the
nameandageproperties of thepersonobject.We define methods (
sayHelloandgetAge) on thepersonobject, which can access the object's properties using thethiskeyword.
Finally, we return the person object from the factory function.
To create instances using the factory function, we invoke the createPerson function and assign the returned object to variables (john and jane).
We can then access the properties (name) and call the methods (sayHello, getAge) on the created objects using the dot notation.
The benefit of using factory functions is that they provide encapsulation and allow for object customization during creation. Each invocation of the factory function creates a new object with its own properties and methods. This pattern is flexible and allows for dynamic object creation and configuration.
Factory functions are an alternative to using classes in JavaScript and are often used in functional programming and object composition scenarios.
About the author
Software Engineer | JavaScript, React, Redux, Node JS, Express, MongoDB
Comments
Join the discussionNo comments yet. Be the first to comment.




