Skip to content

43 Prototypes

Biswajit Sundara edited this page Aug 19, 2023 · 4 revisions

Prototypes are the mechanism by which JavaScript objects inherit features from one another.

1. Get Started

  • Write this object in chrome browser console and then type user.
  • We will observe the name property comes and a bunch of other properties
const user = {
    name: 'Biswajit'
}
  • Similarly for array const hobbies = ['read','eat','play']
  • We can observe there are methods like length, push, pop when we do hobbies.
  • For function also greet. we can observe call, bind, apply etc are popping up
function greet(){
    console.log('Hello');
}
  • It happens to primitive data types also const username = 'Mark' and then do username.
  • We haven't defined those so how those are getting added to our object/variable/function?
  • It happens due to prototype

2. Prototypes

  • In Javascript if we create an object or instance of a function
  • A prototype object is automatically associated with that object or instance.
  • This prototype object is used to look up properties and methods that are not directly present on the object itself.
  • We can access the prototype object using __proto__ or Object.getPrototypeOf(myObj)
const user = {
    name: 'Biswajit'
}
user.__proto__
Object.getPrototypeOf(user)

3. Object Prototype

  • When we create an object (e.g user), its __proto__ property points to Object.prototype
user.__proto__ === Object.prototype   //returns true
  • For arrays it points to Array.prototype hobbies.__proto__ === Array.prototype returns true
  • Similarly we can have String.prototype, Boolean.prototype, Map.prototype
  • All these are further inherited from Object.prototype Array.prototype.__proto__ === Object.prototype returns true
  • For function also it works this way Function.prototype.__proto__ === Object.prototype
  • Object.prototype is the end of the chain, Object.prototype__proto__ will return null.
  • All the data types in Javascript inherits from Object

4. Prototype Chaining

  • We can see a chain getting formed by proto
  • So every variable has a link to the type prototype which further linked to Object prototype
  • Array variable --> Array prototype --> Object prototype
  • This chain is called prototype chaining.
  • Null doesn't have any prototype which indicates the end of the chain.
hobbies.__proto__ === Array.prototype 
Array.prototype.__proto__ === Object.prototype

//we can say
hobbies.__proto__.__proto__ === Object.prototype   //returns true
hobbies.__proto__.__proto__.__proto__    //returns null

Clone this wiki locally