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 can 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 can use that constructor function to create objects.
What Is a Constructor in JavaScript?
Constructors are one of the 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
function NameOfConstructor() {
this.property1 = "Property1";
this.property2 = "Property2";
this.property3 = "Property3";
}
You can create a constructor with the function keyword since it’s essentially like any other function. However, constructors adhere to the following conventions:
- To distinguish them from other functions, use a name for your constructor that begins with a capital letter.
- Constructors use the this keyword differently. Inside a constructor, this refers to the new object that constructor will create.
- Unlike JavaScript functions, constructors define properties and behaviors instead of returning values.
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:
function Student() {
this.name = "Gloria";
this.gender = "Female";
this.age = 19;
}
let femaleStudent = new Student();
In this example, femaleStudent is an object created from the Student constructor. Use the new keyword to call the function as a constructor. This keyword tells JavaScript to create a new instance of Student. You should not call this function without the new keyword because the this inside the constructor will not point to a new object. After construction, femaleStudent has all the properties of Student. You can access and modify these properties just like you would with any other object.
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, the femaleStudent you created above will have properties name, gender, and age with 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.
Thankfully, JavaScript constructors can accept parameters, like any other function. You can change the Student constructor to accept two parameters:
function Student(name, gender) {
this.name = name;
this.gender = gender;
this.age = 19;
}
All objects created from the above will have age set to 19. You can design your constructor this way if there is a property you want all the objects to have.
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.
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:
function Student(name, gender) {
this.name = name;
this.gender = gender;
this.age = 19 ;
this.sayName = function () {
return `My Name is ${name}`;
}
}
The above adds the function sayName to 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:
femaleStudent.sayName()
The Prototype
Earlier, we created Student in a way that all its instances will have an age property with a value of 19. This will result in having a duplicated variable for each Student instance 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 the age property to Student prototype as shown below:
Student.prototype.age = 19;
By doing this, all instances of Student will have the age property. Declaring prototype properties is 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, you can contain all the properties you require in a new object. By doing this, you’ll set all the properties at once. For example:
Student.prototype = {
age: 19,
race: "White",
disability: "None"
}
Remember to set the constructor property when setting prototypes to a new object.
Student.prototype = {
constructor: Student,
age: 19,
race: "White",
disability: "None"
}
You can use this property to check which constructor function created an instance.
Supertypes and Inheritance
Inheritance is a method programmers employ to reduce errors in their applications. It’s a way of sticking to the Don't repeat yourself (DRY) principle.
Suppose you have two constructors—Student and Teacher—that have two similar prototype properties.
Student.prototype = {
constructor: Student,
sayName: function () {
return `My Name is ${name}`;
}
}
Teacher.prototype = {
constructor: Teacher,
sayName: function () {
return `My Name is ${name}`;
}
}
Both these constructors define the sayName method, identically. To avoid this unnecessary duplication, you can create a supertype.
function IndividualDetails(){};
IndividualDetails.prototype = {
constructor: IndividualDetails,
sayName: function () {
return `My Name is ${name}`;
}
};
You can then remove sayName from both constructors.
To inherit the properties from the supertype, use Object.create(). You set the prototype of both constructors to an instance of the supertype. In this case, we set the Student and Teacher prototypes to an instance of IndividualDetails.
Here is it:
Student.prototype = Object.create(IndividualDetails.prototype);
Teacher.prototype = Object.create(IndividualDetails.prototype);
By doing this, Student and Teacher inherit 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 can 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 the class keyword to define classical object-oriented classes. This version of JavaScript also supports a constructor keyword.