What are factory functions in JavaScript ?
In JavaScript, a factory function is a function that returns an object. It is a way of creating and returning objects in a more controlled and customizable manner. Factory functions are a form of design pattern that enables the creation of objects with specific properties and behaviors.
Why it is useful?
If we have complex logic, and we have to create multiple objects again and again that have the same logic, we can write the logic once in a function and use that function as a factory to create our objects. It’s the same as a real-world factory producing products.
Example 1: We have a factory function that will produce new robots with a single logic. Using this we can produce as many objects/robots as we want.
Javascript
function createRobot(name) {
return {
name: name,
talk: function () {
console.log( 'My name is '
+ name + ', the robot.' );
}
};
}
const robo1 = createRobot( 'Chitti' );
robo1.talk();
const robo2 = createRobot( 'Chitti 2.O Upgraded' );
robo2.talk();
|
Output
My name is Chitti, the robot.
My name is Chitti 2.O Upgraded, the robot.
Example 2: In this example, the Person
factory function efficiently creates person objects by encapsulating the process of setting name
and age
properties. Each person object includes a greeting
method for generating a customized message. Instances, such as person1
and person2
, are easily created using the factory function, showcasing a concise and reusable approach to object creation in JavaScript.
Javascript
let Person = function (name, age) {
let person = {};
person.name = name;
person.age = age;
person.greeting = function () {
return (
'Hello I am ' + person.name
+ '. I am ' + person.age
+ ' years old. '
);
};
return person;
};
let person1 = Person( 'Abhishek' , 20);
console.log(person1.greeting());
let person2 = Person( 'Raj' , 25);
console.log(person2.greeting());
|
Output
Hello I am Abhishek. I am 20 years old.
Hello I am Raj. I am 25 years old.
Last Updated :
09 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...