Object Constructors in JavaScript

Object Constructors in JavaScript with Examples

In this article, I am going to discuss Object Constructors in JavaScript with Examples. Please read our previous article where we discussed JavaScript Constructor Function. At the end of this article, you will understand what are Object Constructors in JavaScript and when and how to use Object Constructors in JavaScript with examples.

Object Constructors in JavaScript with Examples

Object constructors and functions are closely related. Keep that in mind as we are learning how to write and use constructors. Let us first gets a deep-dive understanding of object constructor, how to create them, how to use them, and how they work.

Introducing Object Constructors in JavaScript

Object constructors, or “constructors” for short, are nothing but our path to better object creation. Imagine a constructor like a little factory of object creation that can create an endless n number of similar objects. In terms of code, a constructor is quite similar to a function that returns an object: we define it once and invoke it every time we want to create a new object. But as we will see there is a little extra that goes into a constructor.

The best way to see and understand how constructors work is by creating one. Let us create a dog object, with a name, a breed, and a weight and write a constructor to create as many dogs as we need.

Object Constructors in JavaScript

Now, if we were going to define such a dog using an object literal, it will look like this:

var dog = {
            name: "Fido",
            breed: "Mixed",
            weight: 38
        };

The above is just a simple dog object created by an object literal. Now we need to find out how to create a lot of these puppies. But we do not want only a Fido dog, we want a way to create any dog that has a name, a breed, and a weight. And, again, to do that we are going to write some code that looks like a function, with a dash of object syntax thrown in.

How to Create a Constructor in JavaScript?

Using constructors is a two-step process: first, we define a constructor, and second, then we use it to create objects. Let us first focus on creating a constructor. What we want is a constructor that we can use to create dogs, and, more specifically, dogs with properties like names, breeds, and weights. So, we are going to define a function it is called the constructor, which knows how to create dogs. Like this:

How to Create a Constructor in JavaScript?

How to use a Constructor in JavaScript?

As we said using a constructor is a two-step process: first, we create a constructor, then we use it. Now, we have created a Dog constructor, so let us use it. Here is how we do that:

How to use a Constructor in JavaScript?

We can say that to create a Fido, we create a new dog object with the name Fido that is a mixed breed and weighs 38 pounds. In order, to create a new dog object with the name of “Fido”, a breed of “Mixed” and a weight of 38, we start creating an object with the new keyword and follow it with a call to the constructor function with the proper arguments. After this statement is executed, the variable fido will hold a reference to our new dog object. Now that we have a constructor for dogs, we can keep creating them:

var fluffy = new Dog(“Fluffy”, “Poodle”, 30);

var spot = new Dog(“Spot”, “Chihuahua”, 10);

That is much easier than using object literals, and by creating new dog objects in this same way, we know each dog has the same set of properties: name, breed, and weight.

How do Constructors work in JavaScript?

We have seen how to declare a constructor and how to use it to create objects, but we should also look behind the scenes to see how a constructor works. Here is the key: to understand constructors we need to know what the new operator is doing. We will start with the statement we used to create Fido:

var fido = new Dog(“Fido”, “Mixed”, 38);

Now, just look at the right-hand side of the above assignment, where all the action is. Let us follow its execution: The first thing new does is create a new empty object:

How do Constructors work in JavaScript?

Next, new sets this keyword to point to the new object. Remember from chapter this that this holds a reference to the current object our code is dealing with.

How do Constructors work in JavaScript?

With this keyword set up, we now call the function Dog, bypassing “Fido”, “Mixed”, and 38 as arguments.

Object Constructors in JavaScript with Examples

Next, the body of the function is called. Like most constructors, Dog assigns values to properties in the newly created this object.

Object Constructors in JavaScript with Examples

Finally, once the Dog function has completed its execution the new operator returns this keyword, which is a reference to the newly created object. Notice this keyword is returned for us; we do not have to explicitly return it in our code. And after the new object has been returned, we assign that object reference to the variable fido.

Object Constructors in JavaScript with Examples

We can put methods into constructors as well.

By the way, as we know methods in objects are properties too. This just happens to have a function assigned to them. The dog objects that the Dog constructor creates are the same as the dogs from earlier in the chapter. Except that our newly constructed dogs cannot bark because they don’t have a bark method assigned to them. This can easily be fixed because, in addition to assigning values to properties in the constructor, we can set up methods too. Let us extend the code to include a bark method:

We can put methods into constructors as well

What we discussed above is given in the below example.

Example: Object creation in JavaScript, by Using an object constructor with the method
<html>
<head>
    <title> Object creation in JavaScript, by Using object constructor with method example</title>
</head>
<body>
    <script>
        //Using object constructor
        function Dog(name, breed, weight) {
            this.name = name;
            this.breed = breed;
            this.weight = weight;
            this.bark = function () {
                if (this.weight > 25) {
                    document.write(this.name + " says Woof!" + '<br/>');
                } else {
                    document.write(this.name + " says Yip!");
                }
            };
        }

        var fido = new Dog("Fido", "Mixed", 38);
        var fluffy = new Dog("Fluffy", "Poodle", 30);
        var spot = new Dog("Spot", "Chihuahua", 10);
        var dogs = [fido, fluffy, spot];

        for (var i = 0; i < dogs.length; i++) {
            dogs[i].bark();
        }

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

Object creation in JavaScript, by Using object constructor with the method

Be Careful when using Constructor / Calling a constructor function without the new keyword

There is one aspect of constructors we need to be very careful about do not forget to use the new keyword. It is easy to do because a constructor is after all a function, and we can call it without using a new keyword. But if we forget to use a new keyword on a constructor it can lead to buggy code that is hard to troubleshoot. Let us look at what can happen when we forget the new keyword.

Example: Object creation in JavaScript, by Using an Object constructor without the new keyword
<html>
<head>
    <title> Object creation in JavaScript, by Using object constructor without new keyword example</title>
</head>
<body>
    <script>
        //Using object constructor
        function Dog(name, breed, weight) {
            this.name = name;
            this.breed = breed;
            this.weight = weight;
            this.bark = function () {
                if (this.weight > 25) {
                    document.write(this.name + " says Woof!" + '<br/>');
                } else {
                    document.write(this.name + " says Yip!");
                }
            };
        }

        var fido = Dog("Fido", "Mixed", 38);
        fido.bark(); //Uncaught TypeError: Cannot read property 'bark' of undefined
        
    </script>
</body>
</html>
Output:

Object creation in JavaScript, by Using Object constructor without the new keyword

Okay, let us see why this might have happened: Remember that the new first creates a new object before assigning it to this and then calling our constructor function. If we do not use new, a new object will never be created.

That means any references to this in our constructor won’t refer to a new dog object, but rather, will refer to the global object of our application. The global object is the top-level object, which is where global variables get stored. In browsers, this is the window object.

If we do not use a new keyword there is no object to return from the constructor, which means there is no object assigned to the fido variable, so fido is undefined. That is why when we try to call the bark method, we get an error saying the object we are trying to call it on is undefined.

In the next article, I am going to discuss ES6’s new Target Property with Examples. Here, in this article, I try to explain Object Constructors in JavaScript with Examples. I hope you enjoy this Object Constructors in JavaScript article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *