In object-oriented programming, constructors are initializers of objects. They are the templates with which to create multiple objects with the same properties and methods but with different values (assigned initially). In this shot, we are going to talk about constructors in a JavaScript function and the different things associated with them.
It is important to distinguish between an object literal and an object created through a constructor function. As the name suggests, the object literal helps us to create a single object; whereas, constructor functions can help us create multiple objects.
//Object literallet car = {model: "Tesla",year: 2019,reg_no: "TES-2019"};console.log(car)//Constructor functionfunction Car (model, year, reg_no) {this.model = model;this.year = year;this.reg_no = reg_no;};let my_chevy = new Car("Chevrolet", 2015, "CHE-2015");let my_prius = new Car("Toyota", 2020, "TOY-2020");console.log(my_chevy);console.log(my_prius);
There are three things to observe in the code above:
this
is a keyword, not a variable name. It is used to identify the current object in the constructor.new
is a keyword used to create new objects using a constructor function. It creates a new object and then sets the prototype of this object to the constructor function’s prototype property.The constructor function also contains methods associated with objects apart from the attributes of the objects. Let’s look at an example:
//Constructor functionfunction Car (model, year, reg_no) {//attributesthis.model = model;this.year = year;this.reg_no = reg_no;//methodsthis.how_old = function() {console.log("This " + this.model + " is " + (2020 - this.year) + " years old.");};};let my_prius = new Car("Toyota", 2020, "TOY-2020");let my_chevy = new Car("Chevrolet", 2015, "CHE-2015");console.log(my_prius);console.log(my_chevy);my_chevy.how_old()
But what if you want to add more methods and attributes to an existing constructor function? This is where the prototype
comes into play. **prototype**
lets you add more functions and variables to an already existing constructor. Look at the code below to see how to use prototype
:
//Constructor functionfunction Car (model, year, reg_no) {//attributesthis.model = model;this.year = year;this.reg_no = reg_no;//methodsthis.how_old = function() {console.log("This " + this.model + " is " + (2020 - this.year) + " years old.");};};let my_prius = new Car("Toyota", 2020, "TOY-2020");let my_chevy = new Car("Chevrolet", 2015, "CHE-2015");console.log(my_prius);console.log(my_chevy);my_chevy.how_old()Car.prototype.owner = "Brad Pitt";Car.prototype.who_owns = function () {console.log(this.owner + " owns this " + this.model + ".");}my_prius.who_owns();my_chevy.who_owns();
Free Resources