DEV Community

Adewumi Emmanuel Femi
Adewumi Emmanuel Femi

Posted on

Classes Under the Hood

Ever heard the phrase, "in software engineering, everything is an object"? Well, we are going to delve into three major things: How classes in javascript work under the hood, what classes are built on and also the fact that a class is a function basically.

In order to understand how classes work under the hood, we need to touch on two concept in javascript: prototypal inheritance and constructor function.

Constructor Function

When you create a class, you are basically creating a function. This type of function is called a constructor function and it is always initialized with the keyword 'new.' It is a convention in Javascript to start a constructor function with a capital letter.
How to create a constructor function

The (*) represents the creation of the constructor function, (**) represents how to create an object from the constructor function. The line (***) creates an object from the construction function using an inbuilt property 'constructor' (I don't think Ostriches are blue thou). Whenever you create a class you are creating a constructor function.

Prototypal Inheritance

let Animal = { 
  breath: true,
  walk() {
    Alert("All Animal's walk");
  },
};

let Bird = {
  __proto__: Animal, (*) // Bird becomes a prototype of Animal
  fly: true,
};

alert(Bird.walk()) (**) // All Animal's walk
Enter fullscreen mode Exit fullscreen mode

All objects have a property called [[prototype]] this is referenced or called when __proto__ is set on the Bird object to Animal. The line (*) signifies I am inheriting or I am a prototype of Animal; therefore I have access to everything inside the Animal object. The __proto__ can go as deep as possible but an object may not inherit from two at a time i.e you can only inherit from one other object.

How does the above tie into classes and how classes work? Well, when you create a class you create a constructor function and when your class has a constructor you are using the constructor property under the hood.

To sum it all up

Class User{
   constructor(name, age){
      this.name = name;
      this.age = age;
   }
}
const user = new User("David" "2")

function User(name, age){ // This is equivalent to creating a class User
   this.name = name;
   this.age = age;
}
const user = new User()
const user1 = new user.constructor("David" "2") // This is what the User class constructor above calls under the hood
Enter fullscreen mode Exit fullscreen mode
class Animal{
  walk(){
    Alert("All Animal's walk")
  }
}
class Bird extends Animal{ // When you extend animal or you inherit from the Animal class, a __proto__ object property in Bird is created and it refrences Animal
  __proto__: Animal
} 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)