Skip to main content

Building Blocks in JS

Constructor-new

Alright, chai lovers and code enthusiasts! In this lecture we are going learn about constructors . Trust me, this is going to be more exciting than finding an extra samosa in your tiffin!

The Birth of Objects: Constructor Functions

Picture this: You're at a mithai shop, and you want to create dozens of different laddoos. Would you manually shape each one? Of course not! You'd use a mold, right? Well, in JavaScript, constructor functions are like those laddoo molds - they help us create multiple objects with the same structure.

Let's dive in!

What's a Constructor Function?

A constructor function is like the head chef of a bustling kitchen. It knows the recipe, the ingredients, and how to put everything together. Here's the secret recipe:

  1. Start the function name with a capital letter (it's like wearing a chef's hat).
  2. Use it with the key word 'new'.

Let's understand with an example:

function Chai(type, spice) {
  this.type = type;
  this.spice = spice;
  this.isHot = true;
}

let masalaChai = new Chai("Masala", "Ginger");
console.log(masalaChai.type); // "Masala"
console.log(masalaChai.isHot); // true

See what we did there? We created a Chai constructor, and then used it to make a masala chai object. It's like having a chai wala who knows exactly how you like your chai!

The 'new' keyword

Now, let's talk about this 'new' keyword. It's not just a fancy accessory; it's doing some heavy lifting behind the scenes. When you use 'new', JavaScript does a couple of things:

  1. Creates an empty object and assigns it to 'this'.
  2. Runs the function body, adding properties to 'this'.
  3. Returns 'this'.

More about this has been discussed in the previous articles

See how easy it was to create a new object?

function Samosa(filling) {
  // this = {} (secretly created)

  this.filling = filling;
  this.isfried = true;

  // return this (secretly done)
}

let alooSamosa = new Samosa("Spicy Potato");
console.log(alooSamosa.filling); // "Spicy Potato"
console.log(alooSamosa.isfried); // true

It's like magic, but better because it's code!

The Versatility of Constructors

Constructors are like those multi-purpose kitchen gadgets that slice, dice, and make fries. They can do a lot! Let's see how versatile they can be:

function Biryani(rice, meat, spices) {
  this.rice = rice;
  this.meat = meat;
  this.spices = spices;
  this.cook = function() {
    console.log(`Cooking ${this.meat} biryani with ${this.rice} rice and ${this.spices} spices`);
  };
}

let hydBiryani = new Biryani("Basmati", "Chicken", "Secret Hyderabadi");
hydBiryani.cook(); // "Cooking Chicken biryani with Basmati rice and Secret Hyderabadi spices"

Look at that! We not only created properties but also added a method. It's like teaching our biryani how to cook itself!

Case of Return in Constructors

Now, here's where things get a bit tricky. Usually, constructors don't need a return statement. They're happy to return 'this' by default. But what if we do add a return? Well, it depends:

  • If you return an object, it's like saying "Ignore all my hard work, just take this instead".
  • If you return anything else (like a number or string), JavaScript ignores it and returns 'this' anyway.

Let's see this in action:

function Paratha() {
  this.type = "Plain";
  return { type: "Aloo" }; // Overrides everything!
}

let myParatha = new Paratha();
console.log(myParatha.type); // "Aloo"

function Naan() {
  this.type = "Plain";
  return "Garlic"; // Ignored!
}

let myNaan = new Naan();
console.log(myNaan.type); // "Plain"

It's like ordering a plain paratha but getting an aloo one instead, while with the naan, your garlic request is politely ignored!

The Parentheses

Here's a little secret: you can actually omit the parentheses when there are no arguments:

let lassi = new Lassi;
// Same as: let lassi = new Lassi();

But remember, it's like eating pani puri with a fork - technically possible, but not recommended!

Constructor Mode Test: new.target

Sometimes, you want to know if a function was called with 'new' or not. That's where new.target comes in handy. It's like a secret agent that tells you how the function was called:

function Dosa() {
  console.log(new.target);
}

Dosa(); // undefined
new Dosa(); // [Function: Dosa]

This can be super useful! You can even use it to enforce using 'new':

function Idli(type) {
  if (!new.target) {
    return new Idli(type);
  }
  this.type = type;
}

let myIdli = Idli("Rava");
console.log(myIdli.type); // "Rava"

It's like having a bouncer at a club who makes sure everyone enters properly!

Methods in Constructors: Teaching Objects to do things

Constructors aren't just about properties; they can also teach objects how to do things!

function Curry(spiceLevel) {
  this.spiceLevel = spiceLevel;
  this.taste = function() {
    if (this.spiceLevel > 7) {
      console.log("Oof! That's hot!");
    } else {
      console.log("Mmm, delicious!");
    }
  };
}

let vindaloo = new Curry(9);
vindaloo.taste(); // "Oof! That's hot!"

let butterChicken = new Curry(5);
butterChicken.taste(); // "Mmm, delicious!"

See? We're not just creating curries; we're creating curries that know how spicy they are!

Flexibility

The beauty of constructor functions is their flexibility. You can create all sorts of objects with all sorts of properties and methods. It's like having a Swiss Army knife in your coding toolkit:

function Festival(name, date, mainEvent) {
  this.name = name;
  this.date = date;
  this.mainEvent = mainEvent;
  this.celebrate = function() {
    console.log(`Happy ${this.name}! Don't forget the ${this.mainEvent} at ${this.date}`);
  };
}

let diwali = new Festival("Diwali", "November 12", "Lakshmi Puja");
diwali.celebrate(); // "Happy Diwali! Don't forget the Lakshmi Puja at November 12"

let holi = new Festival("Holi", "March 8", "Color Play");
holi.celebrate(); // "Happy Holi! Don't forget the Color Play at March 8"

Built-in Constructors: JavaScript's Ready-Made Molds

JavaScript comes with its own set of constructor functions, like a kitchen that's already stocked with essential tools. You've got Date for dates, Set for unique collections, Map for key-value pairs, and many more. It's like having a fully equipped kitchen ready for you to cook up some code! More about Set and Map is discussed in future lectures.

let today = new Date();
console.log(today); // Current date and time

let uniqueSpices = new Set(["Cumin", "Coriander", "Turmeric", "Cumin"]);
console.log(uniqueSpices); // Set(3) { 'Cumin', 'Coriander', 'Turmeric' }

So there you have it, folks! In this article we have understood how constructors work. We've seen how they create objects, add properties and methods, and even do some magic with the 'new' keyword.

Remember:

  1. Constructor functions are like master chefs - they know the recipe for creating objects.
  2. The 'new' keyword creates a new object and calls the constructor.
  3. You can add properties and methods to make your objects.
  4. Built-in constructors are like ready-made masala mixes - they're there to make your life easier.