JavaScript Object Factories

JavaScript Object Factories with Examples

In this article, I am going to discuss JavaScript Object Factories with Examples. Please read our previous article where we discussed Creating JavaScript Object using Prototype Pattern. At the end of this article, you will understand How to Create JavaScript Object using Object Factories.

JavaScript Object Factories

Object factories are the functions that return objects. Which we already saw in previous design patterns for object creation such as Factory Pattern and Prototype Pattern. They are the template for creating n numbers or as many numbers of objects of one type. What we discussed here is given in the below example.

<html>
<head>
    <title>Object's creation in JavaScript, object factories example</title>
</head>
<body>
    <script>
        // Define an object and Accept parameters
        function createCar(make, model, year) {
            return {
                make: make,
                model: model,
                year: year
            }
        }

        //call methods and create alot of object of any type 
        const mercedez = createCar('Mercedez', 'GT', 2006);
        const tesla = createCar('Tesla', 'Model S', 2019);

        console.log("Using object factories - mercedez: ", mercedez) //returns objects own defined properties and methods
        //{ make: 'Mercedez', model: 'GT', year: 2006 }
        console.log("Using object factories - mercedez: function length: ", Object.getOwnPropertyNames(mercedez).length)
        console.log("Using object factories - mercedez: method type? : ", typeof mercedez);// object


        console.log("Using object factories - mercedez: ", tesla) //returns objects own defined properties and methods
        //{ make: 'Tesla', model: 'Model S', year: 2019 }
        console.log("Using object factories - mercedez: function length: ", Object.getOwnPropertyNames(tesla).length)
        console.log("Using object factories - mercedez: method type? : ", typeof tesla);// object

    </script>
</body>
</html>
Output:

Now run the above code and open browser developer tool and select the Console tab and you should see the following messages in the Console tab.

Creating JavaScript Object using Object Factories with Examples

In the above example, we have created object factories of cars which will create a lot of many objects of car type. The createCar function returned an object. The returned object has a property called make, model, and year whose value is the argument passed to the make, model, and year parameters above respectively.

In the next article, I am going to discuss JavaScript Object Properties with Examples. Here, in this article, I try to explain Creating JavaScript objects using Object Factories with Examples and I hope you enjoy this JavaScript Object Factories article.

Leave a Reply

Your email address will not be published.