Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptWhat are factory functions in JavaScript ?

What are factory functions in JavaScript ?

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 creating new objects 
    // without use of 'new' keyword
    function createRobot(name) {
        return {
            name: name,
            talk: function () {
                console.log('My name is ' 
                + name + ', the robot.');
            }
        };
    }
  
    //Create a robot with name Chitti
    const robo1 = createRobot('Chitti');
  
    robo1.talk();
  
  
    // Create a robot with name Chitti 2.O Upgraded
    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>
  
    // Factory Function creating person
    var Person = function (name, age) {
  
        // creating person object
        var person = {};
  
        // parameters as keys to this object  
        person.name = name;
        person.age = age;
  
        // function to greet
        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. 

RELATED ARTICLES

Most Popular

Recent Comments