The Factory Function is similar to constructor functions/class functions, but instead of using new to create an object, factory functions simply creates an object and returns it.
Factory Functions are a very useful tool in JavaScript. Factory Functions in JavaScript are similar to constructor functions/class functions, but they do not require the use of the ‘this‘ keyword for inner values or the use of the ‘new‘ keyword when instantiating new objects. Factory Functions can contain inner values, methods, etc. just like normal regular functions. Factory Functions differ from regular functions as they always return an object, which will contain any value, method, etc.
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 exactly 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
<script>
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();
</script>
|
Output:
My name is Chitti, the robot.
My name is Chitti 2.0 Upgraded, the robot.
Example 2:
Javascript
<script>
var Person = function (name, age) {
var person = {};
person.name = name;
person.age = age;
person.greeting = function () {
return (
'Hello I am ' + person.name
+ '. I am ' + person.age
+ ' years old. '
);
};
return person;
};
var person1 = Person( 'Abhishek' , 20);
console.log(person1.greeting());
var person2 = Person( 'Raj' , 25);
console.log(person2.greeting());
</script>
|
Output:
Hello I am Abhishek. I am 20 years old.
Hello I am Raj. I am 25 years old.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!