Understanding Prototypes in Javascript

In Javascript, objects inherit properties and methods through prototypes. In fact, Javascript is defined as a prototype-based language. As it is the prototype through which the inheritance happens. for example. An Object inherits its properties through an Object prototype. Which is defined as a __proto__ property.

As We see there are multiple methods declared on the prototype which are all inherited from the underlying base prototype for an object. Let’s say we defined an additional method in this object such as the following:

let obj = {
    a:1,
    b:2,
    print:function(){
        console.log(this.a , this.b)
    }
}

Prototype Chaining

Now if we create an object from this obj. Learn about Object.create from here

let newObj = Object.create(obj)
console.log(newObj)

We see that the newObj that we log to our console has a pretty interesting __proto__ object attached to it.

As we can see our newObj inherited all the properties for our original obj Object. we also see an additional __proto__ attached to the __proto__ of our newObj. This in simple terms is known as Prototype Chaining.

It works in a way that if you are accessing a property on an object. It first tries to find the property within an object . If it fails to do so , It looks for the same in its __proto__. When it fails to find it there it may look in the underlying __proto__ objects(if present). In our above example when we created a new object named ‘newObj’. We saw it was logged in as an empty object on console. Just try and access any property of the underlying ‘obj’ and check what happens.

Defining methods on Prototype

Now, We can define methods and properties in our __proto__ objects. for example.

let obj = {
    a:1,
    b:2,
    print:function(){
        console.log(this.a , this.b)
    }
}
obj.__proto__.showAlert = function(){
    alert(this.a)
}

let newObj = Object.create(obj)
console.log(newObj.showAlert())

So, We defined a function on our base ‘obj’ prototype to show an alert. When we used object.create. This method was also inherited. When we called this method through ‘newObj’. We received the following result.

We covered a lot about javascript prototypes. Few other articles that you may want to read if you want to have some solid js fundamentals.

Leave a Reply