Constructor in JavaScript
Learn via video course
Overview
Constructors in Javascript are a special kind of function used to create and instantiate objects, especially when multiple objects of the same kind need to be created. A constructor defines the object properties and methods. Constructors can be created in two ways using Constructor Functions or using Constructor Methods. We use the new keyword to call a constructor. Javascript also provides built-in constructors such as Array,Object etc
Scope of the Article
- What, why, and how of Constructors in Javascript with easy-to-understand theoretical explanations and coding examples.
- Behind the scenes of constructors
- Adding properties and methods to constructors.
- Calling constructor with and without new keyword
- Constructors with and without parameters
- The article focuses mostly on Constructor functions, Constructor methods are discussed only briefly.
Why Do We Need Constructors?
Consider the situation where you need to invite people to your sibling's marriage and the traditional method of handing out cards is being used. Here you do not create each card by yourself, you simply buy a bunch of cards with a template and fill in the specific details. Similarly in JavaScript, a constructor is used when we want to create multiple objects which have the same properties and methods. Constructors are a special kind of function used to create and instantiate objects.
In Javascript a single object can be created using the object literal ( i.e { }) as follows
Notice that there's a problem here, if we were to create another student object, say student2 then we would again need to write another object as:
This would create a lot of code repetition when there are a large number of objects, hence to create multiple objects of a similar kind we use constructors. They can be created in two ways
- Using the Constructor Function
- Using Constructor Method (ES6+ way)
This article will primarily discuss the first method.
Takeaway: Constructors are used when we want to create multiple objects of same kind.Constructors can be created in two ways using Constructor Functions or using Constructor Methods.
Syntax
A constructor is created similarly to a regular function, the function keyword followed by the name and arguments.
The convention is that the first letter of a constructor's name should to capitalized.
Syntax
Example:
Takeaway: A constructor function is created in the same way as a regular function except that the first letter of its name should be capital.
How to Use a Constructor?
To use a constructor we have to call it and for that, we use the new keyword Let's modify our previous example and see what this means
Output:
Explanation: When we use the new keyword the constructor is called. In the constructor, we bind the given arguments to the properties of the object in the line this.name = name and this.id=id (this in Javascript refers to the current object in this case the objects are student1 and student2) Finally student1 has the value of an object with properties and their values as name:"Tony" and id:101 similar is the case for student2.
Takeaway: To use a constructor we need to use the new keyword this will invoke the constructor.
What Happens When a Constructor is Called?
We have seen that to use a constructor we have to call it now let's see what happens under the hood of that process: When we use the new keyword the followings things happen:
- An empty object is created
- this is set to the newly created object
- The constructor is called
- Inside the constructor the given properties and values are bound to the newly created object by using this.arg = arg
- The constructor returns this which means the object is returned since this is currently set to the newly created object.
Takeaway: When a constructor is called a new empty object is created, the this value is set to this object inside the constructor the properties and values are updated in the object using this keyword and finally the constructor returns this keyword.
Calling a Function Constructor without the New Keyword:
We can call a function constructor without the new keyword just like how we would call a regular function:
As we have learned,the new keyword creates a new object and sets this to it, since we are not using new here the this value will point to the global object. Hence when we try to access the properties of the object we will get the error:
Output:
Takeaway: Calling a constructor without new is possible but gives an error when we try to access the object.
Constructor Mode Test: new.target
- To prevent constructor from being called without new keyword new.target was introduced in ES6.
- If a constructor is called with new then new.target will return a reference to the constructor function and if it is called without new it will return undefined.
- This is useful because we can modify our code to either:
- Force the users to use the new keyword by throwing error.
- We can create the object with new.
Example of scenario 1:
Output:
Explanation: Since we are calling the constructor without the new keyword new.target will return undefined, the if condition is triggered and the error is thrown
Example of scenario 2:
Output
Explanation Since we are calling the constructor without the new keyword new.target will return undefined, the if condition is triggered and a new object is created.
Takeaway: new.target is used to prevent the users from calling the constructor without the new keyword. If a constructor is called with new then new.target will return a reference to the constructor function if not it will return undefined.
JavaScript Built-in Constructors
Javascript also provides some built-in Constructors. Such as:
- Object - Creates new Object object
- Array - Creates new Array object
- String - Creates new String object
- Number - Creates new Number object etc.
Example:
Output:
Takeaway: Javascript has in-built constructors such as Object(),Array(),String(),Number() etc.
JavaScript Constructor Function Parameters
Javascript constructors can be created and invoked with and without function parameters.
How to Define and Invoke Class Constructors with No Parameters?
- To define a constructor with no parameters we must simply not include any parameters in the function definition.
- The properties, if needed, needs to be included inside the definition.
- To invoke the constructor we call the constructor with the new keyword without giving the arguments.
Output
Explanation: A Student object with the given properties and values has been created and assigned to student1 variable.
How to Define and Invoke the Class Constructor with Parameters?
- To define a constructor with parameters we must include the parameters in the function definition.
- The properties and values need to be bound to the object using the this keyword
- To invoke the constructor we call the constructor with the new keyword with the arguments.
Example
Output:
Explanation The student1 and student2 objects are created according to the parameters passed. In the constructor function arguments passed are bound to the objects with this.name = name and this.id=id
Takeaway: Javascript functions can be defined with and without parameters.
Adding Methods to JavaScript Constructor Functions
We can add methods to Javascript constructor functions similar to how we have added other properties which are by using the this keyword. Let us understand this with an example
Output:
Explanation:
- Inside the constructor we first define the function i.e:
function() { console.log("Welcome", this.name) }
- Then we have assigned it a variable welcome
welcome = function() { console.log("Welcome", this.name) }
- Finally we bind it to the object using this
this.welcome = function() { console.log("Welcome", this.name) }
- When the constructor is called whichever object is present in this will invoke the method accordingly hence we see that both student1 and student2 were able to invoke the method.
Takeaway: Methods can be added to Javascript constructor functions similar to how we have added other properties which is by using the this keyword.
Returning from constructors
Usually, constructors do not have return statements as they implicitly return this. But if there exists a return statement then two rules are followed:
- If an object is being returned then the object is returned instead of this.
- If a primitive is returned then the return statement is ignored and this is returned like usual.
Basically, only an object can override this Let us look at these scenarios with examples
Example of Scenario 1
Output:
Explanation: Even though we have passed the name as "Tony" since we are returning an object {name : "Sara"} this overrides the this object (which has the value for name as "Tony") and ultimately we get the name as "Sara".
Example of Scenario 2
Output:
Explanation: Since we are returning a primitive value the return statement is ignored and we see that the student1 variable has an object value and we can successfully access the name property in it.
Takeaway: A constructor always implicitly returns this except when the constructor has a return statement that returns an object, in this case, the object is returned.
JavaScript Object Prototype
- Though it is not obvious there exists an issue when we directly add methods to constructors like we have been doing.
- Each time we create a new Student object we also create a this.welcome() method, it is getting duplicated everytime.
- To handle this we add methods to constructors in Javascript by using prototypes
- A prototype is an object present in every Javascript function and object by default. We can add properties and methods to an object by using this prototype. Let's look at an example of how it can be done:
Example
Output:
Explanation: The prototype of an object can be accessed by using dot(.) notation. Here we access the Student prototype and add a method called programmer to it When the constructor is called for student1 and student2 objects, the programmer method is added to the prototype of these objects. Programmer method added to student1 and student2:
Takeaway: A prototype is a default object present in all functions and objects in Javascript it can be used to add methods and properties to an object.
Constructors in ES6:
We have seen constructor functions till now, in ES6, classes and constructor methods were introduced, these are just syntactic sugar built on top of Constructor functions and prototypes the functionality is the same.
Constructor method syntax:
Constructor methods are used inside classes. They are written as:
Constructor Method Example:
Output:
Explanation:
- Constructor methods work the same as constructor functions.
- When the new keyword is used empty object is created,this is set to the new empty object, the constructor is invoked, and inside the constructor, the properties and values are bound to the object using this and finally this is returned.
Takeaway: Classes and Constructor methods added in ES6 are syntactic sugar created on top of function constructors and prototypes. Constructor methods have the same functionality as Constructor Functions.
Conclusion
- Constructors in Javascript are a special kind of function used to create and instantiate objects, especially when multiple objects of the same kind need to be created.
- Constructors can be created in two ways using Constructor Functions or using Constructor Methods.
- A constructor function is created in the same way as a regular function except that the first letter of its name needs to be capitalized.
- To use a constructor we need to use the new keyword this will invoke the constructor.
- Javascript has in-built constructors such as Object(),Array(),String(),Number() etc.
- A prototype is a default object present in all functions and objects in Javascript it can be used to add methods and properties to an object.