DEV Community

Cover image for Constructor Functions Explained with MASALA DOSA
kamlesh-21
kamlesh-21

Posted on

Constructor Functions Explained with MASALA DOSA

If you've ever been to a South Indian restaurant, you'll know that the variety of dishes available can be overwhelming. From dosas to idlis, each dish has its own unique flavor and texture. But did you know that constructor functions in JavaScript can be used to create objects in a similar way to how a South Indian restaurant creates its dishes?

Imagine that the South Indian restaurant is like a constructor function. Just like the restaurant has a set of predefined recipes and ingredients, a constructor function has a set of predefined properties and methods. For example, a dosa constructor function may have properties such as the type of dosa, the ingredients used, and the cooking time, while its methods may include functions for flipping the dosa and adding toppings.

Here's an example of a dosa constructor function in JavaScript:

function Dosa(type, ingredients, cookingTime) {
  this.type = type;
  this.ingredients = ingredients;
  this.cookingTime = cookingTime;

  this.flip = function() {
    console.log(`Flipping the ${this.type} dosa!`);
  }

  this.addToppings = function(toppings) {
    console.log(`Adding ${toppings} to the ${this.type} dosa!`);
  }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the Dosa constructor function has three properties: type, ingredients, and cookingTime. It also has two methods: flip and addToppings.

To create a new dosa object using the Dosa constructor function, we can use the new keyword and pass in the relevant arguments, as seem below:

const masalaDosa = new Dosa({
  type: 'Masala', 
  ingredients: ['potatoes', 'onions', 'spices'], 
  cookingTime: '10 minutes'
});

Enter fullscreen mode Exit fullscreen mode

In the above example, we create a new masalaDosa object with the property type set to 'Masala', property ingredients set to ['potatoes', 'onions', 'spices'], and property cookingTime set to '10 minutes'.

Now, We can then call the flip and addToppings methods on the masalaDosa object:

masalaDosa.flip(); // Output: Flipping the Masala dosa!
masalaDosa.addToppings('chutney and sambar'); // Output: Adding chutney and sambar to the Masala dosa!

Enter fullscreen mode Exit fullscreen mode

In JavaScript, we use the this keyword to refer to the current object being created or modified. In the Dosa constructor function, we use this to set the values of the type, ingredients, and cookingTime properties, as well as to define the flip and addToppings methods.

So, next time you visit a South Indian restaurant, take a moment to appreciate the way each dish is created using a set of predefined ingredients and cooking methods, just like how a constructor function creates objects in JavaScript.

Top comments (0)