Bytes

Constructors in JavaScript

Module - 8 OOPS in JavaScript
Constructors in JavaScript

Introduction

A constructor is a special function in JavaScript that is used to create and initialize objects. Constructors provide a way to define a template or blueprint for creating objects with specific properties and behaviors. In JavaScript, constructors are used to create objects of a specific class, which is a way to define a type of object and the methods and properties that it will have.

Objects in JavaScript are collections of key-value pairs, where the keys are the property names, and the values are the data or functions associated with those properties. Constructors provide a way to define the properties and methods that an object will have and initialize them when the object is created.

Understanding Constructors with the help of a story

Once upon a time, there was a carpenter named Jack. Jack loved building things and had a workshop where he made beautiful furniture. One day, Jack received a big order from a customer who wanted a dozen identical chairs. Jack realized that it would be tedious to make each chair individually, so he decided to create a chair-making machine.

The chair-making machine would take in specifications like the size of the chair, the type of wood to be used, and the design of the legs. Jack realized that this machine could be programmed to create any type of chair he wanted, just by changing the specifications. He built the chair-making machine using a set of instructions that would allow it to create chairs based on the given specifications.

In JavaScript, constructors are similar to Jack's chair-making machine. Just like the machine takes in specifications to create chairs, a constructor in JavaScript takes in data to create objects. Constructors are essentially functions that are used to create new instances of objects with specific properties and methods.

For example, let's say you're building a website for a restaurant, and you need to create objects for each menu item. You could use a constructor to create objects for each menu item, with properties like the name of the item, the description, the price, and so on. Here's an example of a constructor for a menu item:

function MenuItem(name, description, price) {
  this.name = name;
  this.description = description;
  this.price = price;
}

let burger = new MenuItem("Classic Burger", "A juicy burger with lettuce, tomato, and onion", 10.99);

In this example, the MenuItem constructor takes in three arguments: the name of the menu item, the description, and the price. The constructor then creates a new object with these properties using the "this" keyword. Finally, we create a new instance of the MenuItem object using the "new" keyword and passing in the values for each property.

Just like Jack's chair-making machine could be used to create any type of chair, constructors in JavaScript can be used to create any type of object with specific properties and methods. They are a powerful tool for organizing and managing data in your code.

Creating Constructors in JavaScript

In JavaScript, constructors are defined as functions with a capitalized name. The convention is to use PascalCase (the first letter of each word is capitalized) when naming constructors. For example, a constructor for a car object might be defined like this:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

In this example, the constructor function is called Car, and it takes three parameters: make, model, and year. The this keyword is used to refer to the object being created by the constructor. The properties make, model, and year are assigned to the object using dot notation.

‘new’ Keyword

The new keyword is an essential concept in object-oriented programming and is widely used in JavaScript. It is used to create new instances of objects, which are essentially copies of a prototype object. The constructor function is called with the new keyword, and a new object is created. The object is then assigned to the keyword thisinside the constructor function, and any properties or methods can be added to the object.

Using Constructors to Create Objects

Once you have defined a constructor, you can use it to create objects. To create a new object, you use the new keyword followed by the constructor function and any arguments that the constructor requires. For example, to create a new car object using the Car constructor defined above, you would use the following code:

var myCar = new Car('Honda', 'Accord', 2022);

In this example, a new car object is created with the make "Honda", model "Accord", and year "2022". The object is assigned to the variable myCar, which can be used to access its properties.

Inheritance and Prototypes

One of the most powerful features of constructors in JavaScript is the ability to use inheritance and prototypes. Prototypes allow you to define methods and properties that are shared by all objects created using a constructor. This can be useful for creating objects with common behaviors.

To add a method to a constructor's prototype, you can use dot notation. For example, to add a start method to the Car constructor, you would use the following code:

Car.prototype.start = function() {
  console.log('Starting the ' + this.make + ' ' + this.model);
}

In this example, a new start method is added to the Car constructor's prototype. This method uses the this keyword to refer to the car object being created and logs a message to the console.

To use the start method, you would call it on a car object created using the Car constructor:

var myCar = new Car('Honda', 'Accord', 2022);
myCar.start(); // logs "Starting the Honda Accord"

You can also create a new constructor that inherits properties and methods from an existing constructor using the call method. For example, to create a new constructor for a truck object that inherits properties from the Car constructor, you would use the following code:

function Truck(make, model, year, numWheels) {
Car.call(this, make, model, year);
this.numWheels = numWheels;
}
Truck.prototype = Object.create(Car.prototype);
Truck.prototype.constructor = Truck;

In this example, the Truck constructor calls the Car constructor using the call method to inherit its properties. The Truck constructor also defines a new property, numWheels. The Truck constructor's prototype is then set to a new object created from the Car constructor's prototype, and the constructor property is set to the Truck constructor.

Conclusion

In conclusion, constructors are an essential aspect of object-oriented programming in JavaScript. They allow developers to create and initialize objects with predefined properties and behaviors. By using prototypes and inheritance, constructors can also be used to create new objects with shared properties and methods.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter
Explore Courses

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

view Allview-all

Top Articles toRead

view Allview-all
AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter