JavaScript Object using Prototype Pattern

JavaScript Object using Prototype Pattern

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

JavaScript Object using Prototype Pattern

There are many ways to create an object that we have seen so far out of that there are other ways we can create an object that is from the Object Creation pattern of JavaScript (Factory pattern, Constructor pattern, and Prototype pattern, etc.) among the patterns there is Prototype pattern is there which is a type of object-oriented pattern.

The Prototype pattern is mainly based on JavaScript Prototypical inheritance, where we create an object that is a clone of the original object and acts as a prototype for other objects.

In other words, in terms of prototypical inheritance, the prototype object acts as a blueprint template from which other objects will inherit it when the constructor instantiates them. The Prototype adds the properties of the object to the prototype object. Then, these properties are available and shared among all instances.

JavaScript Object using Prototype Pattern

In the diagram above, we can see that a prototype for the car (a blueprint) is present from which the other types of car objects, car1 and car2, are created. We will be thinking how are these created? In JavaScript, objects can be cloned/shallow copy by using the Object.create() method.

As we already learned in the Object.create() method section, we can also create new objects using the Object.create() method, which allows us to specify the prototype object. The Prototype means JavaScript objects can inherit properties and behavior from other Objects and properties.

This method can be very useful, because it allows us to choose the prototype object for the object we want to create, without the need to define a constructor function.

In JavaScript, all the objects can inherit properties and behavior from other objects. The object we are inheriting from is called Prototype. All the inherited properties of an object can be found in the prototype object of the constructor and we can read the inherited properties of an object by calling the __proto__ i.e.: objectName. __proto__

So far, we saw that when to use the Prototype pattern, we will always have two sections to create it–

  1. one for the constructor itself,
  2. And another for the prototyping area where methods are defined.

And with this, we have a complete introduction to the JavaScript Prototype Pattern.

To clone an object, a constructor must exist to instantiate the first object. Next, by using the keyword prototype variables and methods bound to the object’s structure.

Where to use Prototype Pattern in JavaScript?
  1. The prototype function is used to increase the performance.
  2. It is used to provide the extension to the database operations by creating an object to the other parts of the software application. If other parts of the application need to access this object, it can be done by creating the shallow copy(clone) of the original object or the previously created object.
Advantages of Prototype Pattern in JavaScript:
  1. It provides reusability and moreover with the help of inheritance it provides an extension to the existing object operation by cloning it.
  2. The main advantage of using this pattern is that code reusability, maintenance.
  3. It provides an extension to an existing object.
  4. Functions loaded into memory only one time.
The disadvantages of Prototype Pattern in JavaScript:
  1. Lot of use of the ‘this’ keyword can create confusion
  2. It requires both a constructor and a function prototype.
Example: Object’s creation in JavaScript, by Using Object.create() method
<html>
<head>
    <title>Object's creation in JavaScript, by Using Object.create() method example</title>
</head>
<body>
    <script>
        //car properties and method encapsulation
        var Car = {
            model: 'Audi',
            //color: 'black',
            type: 'Luxury-car', // Default value of properties
            displayType: function () {  // Method which will display type of Animal
                return this.type;
            }
        }

        //Object.create() method syntax. Create new car type called electricCar
        //defining the extra property color with value red black
        var electricCar = Object.create(Car, { color: { value: "red black" } });
        electricCar.displayType(); //Luxury-car

        //Object.create() method syntax. Create new car type called normalCar
        //defining the extra property color with value red
        var normalCar = Object.create(Car, { color: { value: "red" } });
        normalCar.type = 'Normal-car';
        normalCar.displayType(); //Normal-car

        console.log("Using Object.create() method - Car object: ", Car)
        console.log("Using Object.create() method - Car object length: ", Object.getOwnPropertyNames(Car).length)
        console.log("Car type? : ", typeof Car);// object

        console.log("Using Object.create() method - electricCar object without __proto__: ", electricCar)//return empty as there was no property
        //created by electricCar except others are inherited from Car object
        console.log("Using Object.create() method - electricCar object with __proto__: ", electricCar.__proto__)
        console.log("Using Object.create() method - electricCar object length: ", Object.getOwnPropertyNames(electricCar.__proto__).length)
        console.log("electricCar Using Object.create() method type? : ", typeof electricCar);// object
        console.log("Is prototype property of electricCar accessed using __proto__ car?", (electricCar.__proto__) == Car) //true

        console.log("Using Object.create() method - with dot notation-->Property model value of electricCar is: " + electricCar.model);
        console.log("Using Object.create() method - with dot notation-->Property color value of electricCar is: " + electricCar.color);
        console.log("Using Object.create() method - with dot notation-->Property type value of electricCar is: " + electricCar.type);
        console.log("Using Object.create() method - with dot notation-->method displayType of electricCar is: " + electricCar.displayType()); //Luxury-car

        console.log("Using Object.create() method - with bracket notation-->Property model value of electricCar is: " + electricCar['model']);
        console.log("Using Object.create() method - with bracket notation-->Property color value of electricCar is: " + electricCar['color']);
        console.log("Using Object.create() method - with bracket notation-->Property type value of electricCar is: " + electricCar['type']);

        console.log("Using Object.create() method - normalCar object without __proto__: ", normalCar)//return property name Type as there was one property
        //created by normalCar except others are inherited from Car object
        console.log("Using Object.create() method - normalCar object with __proto__: ", normalCar.__proto__)
        console.log("Using Object.create() method - normalCar object length: ", Object.getOwnPropertyNames(normalCar.__proto__).length)
        console.log("normalCar Using Object.create() method type? : ", typeof normalCar);// object
        console.log("Is prototype property of normalCar accessed using __proto__ car?", (normalCar.__proto__) == Car) //true

        console.log("Using Object.create() method - with dot notation-->Property model value of normalCar is: " + normalCar.model);
        console.log("Using Object.create() method - with dot notation-->Property color value of normalCar is: " + normalCar.color);
        console.log("Using Object.create() method - with dot notation-->Property type value of normalCar is: " + normalCar.type);
        console.log("Using Object.create() method - with dot notation-->method displayType of normalCar is: " + normalCar.displayType()); //Normal-car

        console.log("Using Object.create() method - with bracket notation-->Property model value of normalCar is: " + normalCar['model']);
        console.log("Using Object.create() method - with bracket notation-->Property color value of normalCar is: " + normalCar['color']);
        console.log("Using Object.create() method - with bracket notation-->Property type value of normalCar is: " + normalCar['type']);

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

How to Create JavaScript objects using Prototype Pattern

In this example, we have created an object called electricCar using the Car object as a prototype, so the electricCar object will have all the properties of the Car object. We can also use the Object.create() method to create inheritance between objects. Please note that when we directly call the electricCar object to see its content we received an empty object as {} this is because all the inherited properties of the electricCar object from the Car object lies under the proto of electricCar. Hence, in order to read the inherited properties, we have to call __proto__ of the object in this way i.e.: electricCar.__proto__

In the same manner, we have created another car type object called normalCar using the Car object as a prototype, so the normalCar object will have all the properties of the Car object. Also, we use the Object.create() method to create inheritance between objects like we have overridden the type properties of normalCar object from Luxury-car to Normal-car.

Please note that when we directly call the normalCar we received one property in the object as {type: “Normal-car”} this is because we have created/override the type properties of Car inside normalCar with normalCar.type = ‘Normal-car’; and the remaining all the inherited properties of normalCar object from Car object lies under proto of electricCar. Hence, in order to read the inherited properties, we have to call __proto__ of the object in this way i.e.: normalCar.__proto__

Example: Object’s creation in JavaScript, by Using Prototype Pattern
<html>
<head>
    <title>Object's creation in JavaScript, by Using Prototype Pattern example</title>
</head>
<body>
    <script>
        //Prototype function syntax
        // The Constructor (Part 1)
        // Define an object and Accept parameters
        function Flower(name) {
            this.name = name;
        }

        // Function Prototype (Part 2)
        // Add functionality and extend objects
        Flower.prototype.showFlowerName = function () {
            //console.log('This is ' + this.name);
            return 'This is ' + this.name;
        }

        // Calling Prototype based code
        // Resembles traditional OOP styles
        // 'New Up' instances, then call methods on that instance
        const flowerOne = new Flower('Rose');
        const flowerTwo = new Flower('Lily');
        var flower1 = flowerOne.showFlowerName();
        var flower2 = flowerTwo.showFlowerName()

        console.log("Using Prototype pattern method - flowerOne: ", flowerOne) //returns objects own defined properties and methods
        console.log("Using Prototype pattern method - flowerOne function length: ", Object.getOwnPropertyNames(flowerOne).length)
        console.log("flowerOne Using Prototype pattern method type? : ", typeof flowerOne);// object

        console.log("Using Prototype pattern method - flowerTwo: ", flowerTwo) //returns objects own defined properties and methods
        console.log("Using Prototype pattern method - flowerTwo function length: ", Object.getOwnPropertyNames(flowerTwo).length)
        console.log("flowerOne Using Prototype pattern method type? : ", typeof flowerTwo);// object

        console.log("Using Prototype pattern - Object creation of flowerOne: " + flower1);
        console.log("Using Prototype pattern - Object creation of flowerTwo: " + flower2);

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

Object's creation in JavaScript, by Using Prototype Pattern

In the above example, we have created the prototype method Flower for creating different types of flowers object and returning their reference in turn.

Also, we have created two different objects for it named as flowerOne and flowerTwo for calling the prototype pattern constructor Flower, and when we are passing the flower name such as Rose for flowerOne and Lily for flowerTwo objects it returns new instances of flowers whenever called by creating an extension of Flower constructor with the help of prototype.

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

Leave a Reply

Your email address will not be published.