In the Previous Tutorial we learned how to create objects by using Factory Functions. In this tutorial we’ll learn the third and the final way to create objects – Constructor Function
What is a Constructor Function?
A Constructor Function on its own is not different from regular JavaScript functions. The real fun starts when it is used with the new keyword.
Before delving into the new keyword, let us first take a look at the Constructor Function.
Here is how we can transform the same createCar Factory Function from the Previous Tutorial and make it a Constructor Function –
function Car(make, model){
this.make = make;
this.model = model;
this.run = function(){
console.log(this.make + ' ' + this.model + ' is running...');
}
}
This function takes two arguments – make and mode.
Did you Notice?
The convention to name the Constructor Function is similar to classes in other programming languages like Java, Python, C# etc. Unlike Factory Functions it is not in camelCase with first lower character, the first character in Constructor Function is upper case. It is Car, not createCar.
Hey, what is the this keyword doing there while defining make/model property and run method?
Glad you noticed it. The this keyword in the Constructor Function refers to the object that invoked that function. We are setting make & model properties and run() method on that object.
But which object called that function? I cannot see anything…
Relax champ. We’ve just declared a function. If you are from Java/Python/C# type of languages background, it is similar to when we declare a class in those languages. No object is created until we explicitly create an object using the new keyword.
To create an object by using Constructor Function, you need to do this –
var car = new Car('Volkswagen', 'Golf');
What just happened when this command ran?
- The new operator created an empty object in memory.
- Some more things happened in the background that we’ll discuss in the Next Tutorial.
- Next, it called the Car() function in the context of this empty object. Which means in simple terms – The this keyword in the Constructor Function started referring to that empty object.
- It makes the properties(make, model) and methods(run) set on that empty object.
- The empty object is no more empty. It has properties and methods as defined by its constructor function.
- Finally, that object is returned from the Constructor Function, which is now being referred by the car variable.
Do you Know?
You can also explicitly return anything from the Constructor Function. When no return statement is encountered, JavaScript returns the newly created object. But you would rarely find explicit return statement in a Constructor Function because doing so doesn’t make any sense. JavaScript has done the dirty job for you, enjoy the returned object.
Updated myjs.js file
function Car(make, model){
this.make = make;
this.model = model;
this.run = function(){
console.log(this.make + ' ' + this.model + ' is running...');
}
}
var car = new Car('Volkswagen', 'Golf');
car.run();
Save the file and if the Live Server is running, you should see the message in browser console.
Volkswagen Golf is running...
Lets Experiment
Go to the browser console and create a new car. In the next command pass the object name to verify if it is created correctly –
Some more Experiment
Create one more car but this time DROP the new keyword. In the next command pass the object name to verify if it is created correctly –
Hey, where is my Tesla. Why is it undefined?
Looks like you were not attentive to the tutorial. I explained it very clearly while creating object. It is very important to remember.
Never skip the new keyword while creating object by using Constructor Function
If would highly recommend you to read the above section again – What just happened when this command ran – var car = new Car(‘Volkswagen’, ‘Golf’);
Ok, I read that section again and I know the new keyword creates an empty object. But what if I drop it?
In addition to creating an empty object the new keyword does one more thing – It makes the this keyword inside the Constructor Function refer to THAT empty object.
In case you drop the new keyword the this keyword in Constructor Function refers to the global object. window in case of browser and global in case of node.
Lets Experiment one more time
Run the following command in the browser console window and see the magic – window.run()
Try accessing the make and model properties of the window object –
Did you Notice?
All properties and methods of Car Constructor Function is assigned to the window object because you did not provide the new keyword. So never ever skip the new keyword. It may cause destructive behaviour for the application.
But you taught three different ways to create objects – Object Literal, Factory Function and Constructor Function. Which one should I use to create objects?
Using Constructor Function is more preferred among developers who come from other object oriented programming languages like Java, C#, Python etc. It has similar syntax to Class in those languages. But always remember – There is no concept of class in JavaScript.
Wait… you told there are few more things that happened in the background in this section – What just happened when this command ran?
Why don’t you read the Next Tutorial to understand what all happens in the background when we use the new operator. Trust me, it’s interesting to know.