Skip to main content

Command Palette

Search for a command to run...

new Keyword in Js

Updated
2 min read
new Keyword in Js

have you ever heard of word new ? have you ever used it ? I will try to link that new to this new in js .

in real life whenever you used new with something it means it is not used by anybody and you will be first person to open it and use it .

in an almost similar analogy new keyword in js creates a new instance in memory and there are some steps involved that i will tell new next.

there are basically 4 steps involved :

  1. it creates a fresh object in memory

  2. then it sets prototype of this new object as the constructor's prototype .

  3. then it binds this context with the constructor to this new object

  4. finally returns the new object .


constructor function , prototype , instance creation

this is the method which is of the same name as class and used to make instances from that class

class Car{
    constructor(name, model , price){
        this.name= name
        this.model = model
        this.price = price 
    }
    function race(){
        console.log(`${this.model} is racing at 100km/h`
    }
}

let myCar= new Car( "maruti","alto" ,"898779")

the class Car has Car constructor that is used to make myCar object having same methodd and attributes as Car .

lets look at all the steps now .

  • a new empty object is created in memory

  • its prototype is linked to prototype of Car class meaning it has all methods that the class Car has .

  • then this context of object is bind with constructor .

  • finally a new object is returned to variable myCar.