Table of contents
- What is Constructor?
- Why do we need Constructor?
- Ways to create a constructor
- Constructor Function
- What Happens When a Constructor is Called?
- Returning from constructors
- Calling a Function Constructor without the New Keyword
- new.target
- Adding Methods to Constructor Functions
- Cons of adding methods directly to the Constructor Function
- Adding Methods Using prototype
- JavaScript Built-in Constructors
- Final Words
What is Constructor?
Constructor in JavaScript is a special kind of function that is used to create and instantiate multiple objects of the same kind.
Why do we need Constructor?
In JavaScript, a single object can be created using the object literal { }
const student1 = {
name : "Bobby"
id : 18
}
If we want to create multiple objects of the same type as of student1 object, then we would have to create objects using object literal { } again and again:
const student2 = {
name : "Deadpool"
id : 19
}
const student3 = {
name : "John Wick"
id : 20
}
This would create a lot of code repetition for a large number of objects, hence to create multiple objects of a similar kind we use constructors.
Ways to create a constructor
Using the Constructor Function
Using Constructor Method (ES6+ way)
In this blog, we will discuss the first method only.
Constructor Function
A constructor function is created in the same way as a regular
function.
The first letter of its name should be capitalized
.
To call a constructor, we use new
keyword.
Constructors do not have return statements as they implicitly return this
.
this
inside the constructor function points to the object that is created from that constructor.
// Creating constructor
function Character(name, power){
this.name = name;
this.powers = power
}
// Calling the constructor using new keyword
let deadpool = new Character('Deadpool', 'accelerated healing factor')
let batman = new Character('Batman', ' Intellect, Fighting skills & Wealth')
console.log(deadpool)
// { name: 'Deadpool', powers: 'accelerated healing factor' }
console.log(batman)
// { name: 'Batman', powers: 'Intellect, Fighting skills & Wealth' }
What Happens When a Constructor is Called?
When we use the new
keyword the followings things happen:
An empty object is created
this
is set to the newly created objectThe constructor is called
Inside the constructor, the given properties and values are attached to the newly created object by using
this.arg = arg
Then the constructor returns
this
which means the object is returned sincethis
is currently set to the newly created object.
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 returnedexplicitly
then that object will be returned andthis
will be ignored.
function Student(name,id){
this.name = name
//returning an object
return {name : "Deadpool"}
}
const student1 = new Student("Bobby")
console.log(student1.name) // Deadpool
- If a
primitive
is returnedexplicitly
then it will be ignored andthis
will be returned as usual.
function Student(name,id){
this.name = name
//returning primitive
return 42
}
const student1 = new Student("Bobby")
console.log(student1.name) // Bobby
Calling a Function Constructor without the New Keyword
Calling a constructor without new
is possible but this
will point to the global object
and gives an error when we try to access the object.
function Character(name){
this.name = name;
}
const deadpool = Character('Deadpool');
console.log(deadpool.name)
// TypeError: Cannot read property 'name' of undefined
As we have learned, the new keyword creates a new object and sets this
to that object, since we are not using new
keyword here this
value will point to the global object
. Hence when we try to access the properties of the object we will get the error
.
new.target
To prevent the constructor from being called without new
keyword new.target
was introduced in ES6.
If a constructor is called with
new
keyword thennew.target
will return a reference to the constructor function.If it is called without
new
keyword it will returnundefined
.
This is useful because we can modify our code to either:
Force the users to use the
new
keyword by throwing an error.We can create the object with
new
.
Example of scenario 1:
function Student(name) {
if (!new.target) {
throw Error("Use the new keyword to call constructor");
}
this.name = name
}
const student1 = Student("Bobby")
// Error: Use the new keyword to call constructor
Example of scenario 2:
function Student(name) {
if (!new.target) {
return new Student(name)
}
this.name = name
}
let student1 = Student("Bobby")
console.log(student1.name); // Bobby
Adding Methods to Constructor Functions
Methods can be added to Javascript constructor functions similar to how we have added other properties by using this
keyword.
function Character(name, universeName){
this.name = name;
this.universeName = universeName;
this.universe = function(){
return(`${name} is from ${universeName}`)
}
}
// Calling the constructor using new keyword
let deadpool = new Character('Deadpool', 'Marvel')
let batman = new Character('Batman', 'DC')
console.log(deadpool.universe())
// Deadpool is from Marvel
console.log(batman.universe())
// Batman is from DC
Cons of adding methods directly to the Constructor Function
There exists an issue when we directly add methods to constructors using this
.
Each time we create a new Character
object we also create a this.universe()
method, it is getting duplicated every time.
To handle this we add methods to the constructor function by using prototypes
.
A prototype
is an object present in every JavaScript object by default. By using the prototype property, it will add methods to the prototype object instead of creating the method every time.
Adding Methods Using prototype
// Creating constructor
function Character(name, universeName){
this.name = name;
this.universeName = universeName;
}
// Adding method into constructor using prototype
Character.prototype.universe = function(){
return(`${this.name} is from ${this.universeName}`)
}
// Calling the constructor using new keyword
let deadpool = new Character('Deadpool', 'Marvel')
let batman = new Character('Batman', 'DC')
console.log(deadpool.universe())
// Deadpool is from Marvel
console.log(batman.universe())
// Batman is from DC
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:
let str = new String("Bobby"); // A new String object
let num = new Number(18); // A new Number object
let obj = new Object(); // A new Object object
let arr = new Array("Dope","Blogs"); // A new Array object
Final Words
And that’s it for this blog.
I hope you’ve found this blog a good referencing resource and thank you for reading.
If this blog was helpful, please do like, comment and share. Thanks, see you in the next article.✌️