Skip to main content

Command Palette

Search for a command to run...

What Really Happens When You Use new?

Published
What Really Happens When You Use new?

What the new keyword does

  • When you create a new instance with the new keyword, a brand new empty object {} is created.

  • In JavaScript, every function has a prototype. Even objects themselves have a prototype, so the prototype creates a bridge between the empty object and the function and links them together.

  • Now the this keyword becomes active after the link and binds the value. Whoever calls it will bind with the caller reference — it binds this to the new object.

  • If you check any class, there is no return statement. So the final work is done by the new keyword, which automatically returns the newly created object (the constructor explicitly returns the object).

function TataCar(chassisNumber, modelName) {  
  this.chassisNumber = chassisNumber;  
  this.modelName = modelName;
  this.fuelLevel = 100;  
}

// created own method using prototype
TataCar.prototype.status = function () {
  return `Tata \({this.modelName} #\){this.chassisNumber} | Fuel: ${this.fuelLevel}`;
};

const car1 = new TataCar("MH-101", "Nexon");
const car2 = new TataCar("DL-202", "Harrier");

console.log(car1.modelName);
// console.log(car2.modelName);
// console.log(car1.status());
console.log(car2.status());

const car1 = new TataCar("MH-101", "Nexon");
const car2 = new TataCar("DL-202", "Harrier");

Behind the scene
let car1 = {}; // empty object created
Prototype creates a bridge
car1.__proto__ = TataCar.prototype;
Now car1 is linked to:
TataCar.prototype.status
car1.status();
works even though status is not inside car1.
prototype creates bridge between empty object and function

this binds to new object

Inside constructor:
this.chassisNumber = "MH-101";
this.modelName = "Nexon";
this.fuelLevel = 100;

Since this === car1:

No return in constructor:

function TataCar(...) {
// no return
}

new automatically returns object

console.log(typeof car1.status) // function 
car1.status === car2.status // true

Now check the below factory function

function createAutoRickshaw(id, route) {
  return {
    id,
    route,
    run() {
      return `Auto \({this.id} running on \){this.route}`;
    },
  };
}

const auto1 = createAutoRickshaw("UP-1", "Lucknow-kanpu");
const auto2 = createAutoRickshaw("UP-2", "Agra-Mathura");

console.log("TypeOf", typeof auto1.run); // function
auto1.run === auto2.run // false

Constructor functions (with new) share methods via prototype (same reference), while factory functions create a new copy of methods for each object.

newshared methods (memory efficient)

factorynew method copy each time (memory heavy)

Summary

Use constructor + new when creating many objects with shared behavior

  • Use factory functions for simple, small use cases