Understanding Constructors in JavaScript

JavaScript is an established language but it only added support for classic object-oriented programming (OOP) in ES6. Until it added features like class declarations, JavaScript handled OOP using a lesser-known prototype-based paradigm. With either approach, however, you may create complex applications that use object-based features.

A constructor in prototypical JavaScript looks much like any other function. The main difference is that you could use that constructor function to create objects.

4

What Is a Constructor in JavaScript?

Constructors are one ofthe fundamental concepts in object-oriented programming. A constructor is a function you can use to create an instance of an object. As well as creating a new object, a constructor specifies the properties and behaviors that will belong to it.

Constructor Syntax

You can create a constructor with thefunctionkeyword since it’s essentiallylike any other function. However, constructors adhere to the following conventions:

Using a Constructor to Create New Objects

In JavaScript, using a constructor to create an object is an easy task. Here’s a simple constructor with an invocation following it:

In this example,femaleStudentis an object created from theStudentconstructor. Use thenewkeyword to call the function as a constructor. This keyword tells JavaScript to create a new instance ofStudent. You should not call this function without thenewkeyword because thethisinside the constructor will not point to a new object. After construction,femaleStudenthas all the properties ofStudent. You can access and modify these properties just like you would with any other object.

A dark monitor displaying TypeScript code in the VSCode editor.

Important Things to Know About JavaScript Constructors

Working with constructors can be so tiring, and at the same time, it can be an easy task. Here are some important things any developer should know about working with constructors.

Using Constructors With Arguments

You can extend a constructor to receive arguments. This is very important if you’re looking to write responsive, flexible code.

Whenever you create an object from a constructor, the object will inherit all the properties declared in the constructor. For example, thefemaleStudentyou created above will have propertiesname,gender, andagewith fixed initial values. While you can change each property manually, it would be a lot of work if you were writing a program using many objects.

A laptop showing lines of code in an IDE

Thankfully, JavaScript constructors can accept parameters, like any other function. You can change theStudentconstructor to accept two parameters:

All objects created from the above will haveageset to19.You can design your constructor this way if there is a property you want all the objects to have.

Photo of a programmer sitting at a computer

You can now define unique objects from the same constructor by passing in different arguments.

Arguments make constructors more flexible. They save time and encourage clean code.

USB-C port on the Google Pixel 8a

Defining Object Methods

A method is an object property that is a function. Methods enhance your code in OOP as it adds different behaviors to your objects. Here is an example:

The above adds the functionsayNameto the constructor.

Suppose you use this constructor to create an object that you store in a variable,femaleStudent. You can then call this function with the code below:

The Prototype

Earlier, we createdStudentin a way that all its instances will have anageproperty with a value of19.This will result in having a duplicated variable for eachStudentinstance you create.

To avoid this duplication, JavaScript uses the concept of prototypes. All objects created from a constructor share the properties of its prototype. You can add theageproperty toStudentprototype as shown below:

By doing this, all instances ofStudentwill have theageproperty. Declaringprototype propertiesis a way to reduce duplicate code in your application. It makes your code as standard as possible.

A Prototype Property Can Be an Object

You can add Prototype properties individually as explained above. But if you have many properties to add, this can be inconvenient.

As an alternative, it’s possible to contain all the properties you require in a new object. By doing this, you’ll set all the properties at once. For example:

Remember to set theconstructorproperty when setting prototypes to a new object.

you could use this property to check which constructor function created an instance.

Supertypes and Inheritance

Inheritanceis a method programmers employ to reduce errors in their applications. It’s a way of sticking to theDon’t repeat yourself (DRY)principle.

Suppose you have two constructors—StudentandTeacher—that have two similar prototype properties.

Both these constructors define thesayNamemethod, identically. To avoid this unnecessary duplication, you can create asupertype.

You can then removesayNamefrom both constructors.

To inherit the properties from the supertype, useObject.create(). You set the prototype of both constructors to an instance of the supertype. In this case, we set theStudentandTeacherprototypes to an instance of IndividualDetails.

Here is it:

By doing this,StudentandTeacherinherit all the properties of the supertype,IndividualDetails.

This is how to practice DRY in OOP using supertypes.

Constructors Are Game Changers

Constructors are a key component of JavaScript, and mastering their functionality is crucial for developing OOP JavaScript applications. you’re able to use a constructor to create objects that share properties and methods. You can also use inheritance to define object hierarchies.

In ES6, you can use theclasskeyword to define classical object-oriented classes. This version of JavaScript also supports aconstructorkeyword.

If you’re looking for tips on how to create JavaScript classes, you’ve come to the right place. Here’s how to do it.

I plugged random USB devices into my phone and was pleasantly surprised by how many actually worked.

The fix was buried in one tiny toggle.

Sometimes the smallest cleaning habit makes the biggest mess.

It’s not super flashy, but it can help to keep your computer up and running.

Taming data is easier than it looks.

Technology Explained

PC & Mobile