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 How to Create JavaScript Object Using the new Object() Method.

Using an object constructor (using the new keyword)

In the previous chapter, we have created an object using the object literal (or initializer) syntax.

var person = {
    name: "Maria", age: 22, favColor: "green"
};

This allows us to create only a single object. Sometimes, we need to set an “object type” that can be used to create a number of objects of a single type. The standard way to create an “object type” is to use an object constructor function.

Syntax:
function ObjName(name) {
    this.name = name;
}

//Object constructor syntax
var myobj = new ObjName("my object");

In this method, the constructor function is used to define the object and this keyword is used to assign value to the properties. An instance of the object is created using a new keyword. Here, we need to create a function with arguments. Each argument value can be assigned in the current object by using this keyword in the function.

Note: this keyword refers to the current object. Note that this is not a variable but a keyword, and its value cannot be changed.

An object can have a property that is itself another object. For example, suppose we define an object called a person as follows and then create a new object i.e.: instantiate 2person objects as mentioned below:

function person(name, age, color) {
    this.name = name;
    this.age = age;
    this.favColor = color;
}

The above function name person is an object constructor, which accepts parameters and assigns them to the object properties using this keyword.

Creating Objects using Constructor in JavaScript

Once we have an object constructor, we can use the new keyword to create new objects of the same type. And then create a new object i.e.: Instantiate two new person objects as follows:

var p1 = new person("John", 42, "green");
var p2 = new person("Maria", 21, "red");

document.write(p1.age); // Outputs 42
document.write(p2.name); // Outputs "Maria"

p1 and p2 are now objects of the person type. Their properties are assigned to the corresponding values. The object’s properties can be accessed by using the dot notation or bracket notation syntax, as we did before.

What we discussed above is given in the below example.
<html>
<head>
    <title>Object's creation in JavaScript, by Using Object constructor example</title>
</head>
<body>
    <script>
        //Object constructor syntax
        function person(name, age, color) {
            this.name = name;
            this.age = age;
            this.favColor = color;
        }

        var john = new person("John", 42, "green");
        var maria = new person("Maria", 21);

        console.log("Using Object constructor - john object: ", john)
        console.log("Using Object constructor - john object length: ", Object.getOwnPropertyNames(john).length)
        console.log("john using Object constructor type? : ", typeof john);// object
        console.log("Using Object constructor - maria object: ", maria)
        console.log("Using Object constructor - maria object length: ", Object.getOwnPropertyNames(maria).length)
        console.log("maria using Object constructor type? : ", typeof maria);// object

        console.log("Using Object constructor - with dot notation-->Property name value of john is: " + john.name);
        console.log("Using Object constructor - with dot notation-->Property age value of john is: " + john.age);
        console.log("Using Object constructor - with dot notation-->Property favColor value of john is: " + john.favColor);
        console.log("Using Object constructor - with bracket notation-->Property name value of maria is: " + maria['name']);
        console.log("Using Object constructor - with bracket notation-->Property name value of maria is: " + maria['age']);
        console.log("Using Object constructor - with bracket notation-->Property name value of maria is: " + maria['favColor']);
    </script>
</body>
</html>

Now run the above code, open the browser developer tool by pressing the F12 key and have a look at the Console tab and you should see the following logs

Object's creation in JavaScript, by Using Object constructor example

Object creation in JavaScript, by Using Object constructor example

Object Constructors in JavaScript:

Object constructors and functions are closely related. Keep that in mind as we are learning how to write and use constructors. Let’s first gets deep dive understanding of object constructor, how to create, how to use 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’s create a dog object, with a name, a breed, and a weight and write a constructor to create as many dogs as we need.

Introducing 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 don’t 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’re 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 secondly, then we use it to create objects. Let’s 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’s use it. Here’s 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 by 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 the constructors work in JavaScript?

We have seen how to declare a constructor and also how to use it to create objects, but we should also take a look behind the scenes to see how a constructor actually works. Here’s the key: to understand constructors we need to know what the new operator is doing.

We’ll start with the statement we used to create fido:

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

Now, just take a look at the right-hand side of the above assignment, where all the action is. Let’s follow its execution:

1: The first thing new does is create a new empty object:

The first thing new does is create a new empty object:

2: 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.

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.

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

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

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

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

5: 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 don’t 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.

How do the constructors work in JavaScript?

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 can’t bark because they don’t have a bark method assign 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’s 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’s creation in JavaScript, by Using object constructor with the method
<html>
<head>
    <title>Object’s 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>

Now run the above code and you will get the following output in the browser.

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

Be Careful when using Constructor in JavaScript

There is one aspect of constructors we need to be very careful about: don’t forget to use the new keyword. It’s 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’s take a look at what can happen when we forget the new keyword. What we discussed above is given in the below example.

Example: Object’s creation in JavaScript, by Using object constructor without the new keyword
<html>
<head>
    <title>Object’s 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>

Now run the above code, open the browser developer tool by pressing the F12 key and have a look at the Console tab and you should see the following error message

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

Okay, let’s 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 don’t 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 object is the window object.

If we don’t 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’s 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.

Object literals are still useful

We have had some discussion of object constructors versus object literals, and also mentioned that object literals are still quite useful, but we really haven’t seen a good example of that. Well, let’s take a small example of making mass-produce car objects. And will focus on a reworking of the Car constructor code, so we can see where using some object literals actually cleans up the code and makes it more readable and maintainable.

Let’s look at the Car constructor and see how we might be able to clean it up a bit.

function Car(make, model, year, color, passengers, convertible, mileage) {
            this.make = make;
            this.model = model;
            this.year = year;
            this.color = color;
            this.passengers = passengers;
            this.convertible = convertible;
            this.mileage = mileage;
            this.started = false;
            this.start = function () {
                this.started = true;
            };
            //rest of the methods here
}

Notice we are using a lot of parameters here. We count seven. The more we add and we always end up adding more as the requirements for objects grow, the harder it becomes to read.

And when we write code that calls this constructor, we have to make sure we get the arguments all in exactly the right order. So, the problem we are focusing on here is that we have a lot of parameters in the Car constructor, making it difficult to read and maintain. It’s also difficult to write code to call this constructor. While that might seem a little tedious, it actually causes more bugs than we might think, and not only that, they’re often creepy bugs that are hard to diagnose at first.

They’re hard to diagnose because if we switch two variables, the code is still syntactically correct, but it doesn’t function correctly because we have switched two values. However, there is a common technique that we can use when passing all these arguments that can be used for any function, whether or not it’s a constructor.

The technique works like this, take all your arguments, put them in an object literal, and then pass that literal to our function—that way we are passing all our values in one container i.e.: the literal object and we don’t have to worry about matching the order of the arguments and parameters.

Let’s rewrite the code to call the Car constructor, and then do a slight rework of the constructor code to see how this works.

Reworking the arguments as an object literal

Let’s make the call to the Car constructor and rework its arguments passed into an object literal:

var cadi = new Car(“GM”, “Cadillac”, 1955, “tan”, 5, false, 12892);

All we need to do is to take each argument and place it in an object literal with a proper property name. Here we have used the same property names used in the constructor.

//object literals
var cadiParams = {
            make: "GM",
            model: "Cadillac",
            year: 1955,
            color: "tan",
            passengers: 5,
            convertible: false,
            mileage: 12892
};

We have kept the same order. And then we can write again the call to the Car constructor like this:

//object literals
var cadiParams = {
            make: "GM",
            model: "Cadillac",
            year: 1955,
            color: "tan",
            passengers: 5,
            convertible: false,
            mileage: 12892
};

//Car constructor
var cadi = new Car(cadiParams); 

If we look at the above code not only it is cleaner but also a lot more readable. And then we are passing the object literal variable as a single argument to the Car constructor. But the work is not done yet because the constructor itself is still expecting seven arguments, not one object. Let’s rework the constructor code, and then we will test it.

Reworking the Car constructor

Now we need to remove all the individual parameters in the Car constructor and replace them with properties from the object that we are passing in. We will call that parameter as params. We also need to modify the code a little bit to use this object. Here is how:

//object literals
var cadiParams = {
            make: "GM",
            model: "Cadillac",
            year: 1955,
            color: "tan",
            passengers: 5,
            convertible: false,
            mileage: 12892
};

//Car constructor
var cadi = new Car(cadiParams); 

No changes in the above object literal and constructor, we have just reproduced the object literal and the call to the Car constructor from the previous page.

Object Constructors in JavaScript with Examples

What we discussed above is given in the below example.

Example: Object’s creation in JavaScript, by Using object literal with Object constructor
<html>
<head>
    <title>Object's creation in JavaScript, by Using object literal with Object constructor example</title>
</head>
<body>
    <script>
        //object literals
        var cadiParams = {
            make: "GM",
            model: "Cadillac",
            year: 1955,
            color: "tan",
            passengers: 5,
            convertible: false,
            mileage: 12892
        };

        //calling Car constructor
        var cadi = new Car(cadiParams);
        cadi.start(); //constructor method
        cadi.drive();
        cadi.stop();

  //Car constructor
        function Car(params) {
            this.make = params.make;
            this.model = params.model;
            this.year = params.year;
            this.color = params.color;
            this.passengers = params.passengers;
            this.convertible = params.convertible;
            this.mileage = params.mileage;
            this.started = false;
            this.start = function () {
                this.started = true;
            };
            this.stop = function () {
                this.started = false;
            };
            this.drive = function () {
                if (this.started) {
                    alert("Zoom zoom!");
                } else {
                    alert("You need to start the engine first.");
                }
            };
        }
    </script>
</body>
</html>
Output:

Object's creation in JavaScript, by Using object literal with Object constructor

In the next article, I am going to discuss Object Instances in JavaScript with Examples. Here, in this article, I try to explain Object Constructors in JavaScript with Examples and I hope you enjoy this Object Constructors in JavaScript article.

Leave a Reply

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