Yogesh Chauhan's Blog

What is Prototypal Inheritance in JavaScript?

in JavaScript on November 21, 2020

Let’s start from basics. One by one.

What are Object prototypes?

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

JavaScript is often described as a prototype-based language — to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from.

An object’s prototype object may also have a prototype object, which it inherits methods and properties from, and so on.

This is called a prototype chain, and explains why different objects have properties and methods defined on other objects available to them.

Prototypal inheritance

In programming, we often want to take something and extend it.

For example, let’s say we have a user object with its properties and methods, and we want to make admin and guest as users slightly modified versions of the user object.

We’d like to reuse what we have in user, not copy its methods, just build a new object on top of it.

In that case, Prototypal inheritance feature will be really helpful.

[[Prototype]]: In JavaScript, objects have a special hidden property [[Prototype]] which is either null or references another object. That object is called “a prototype”.

💡 When we want to read a property from object, and it’s missing, JavaScript automatically takes it from the prototype. In programming, such thing is called “prototypal inheritance”.

The property [[Prototype]] is internal and hidden, but there are many ways to set it.

One of them is to use the special name __proto__, for example:


let animal = {
    eats: true
};

let rabbit = {
     jumps: true
};
    
rabbit.__proto__ = animal;

//output

{ eats: true }

If we look for a property in rabbit, and it’s missing, JavaScript automatically takes it from animal.

For example:


let animal = {
    eats: true
};
let rabbit = {
    jumps: true
};

rabbit.__proto__ = animal; 

// output
// we can find both properties in rabbit now:
alert( rabbit.eats ); // true
alert( rabbit.jumps ); // true

Here the line rabbit.__proto__ = animal; sets animal to be a prototype of rabbit.

Then, when alert tries to read property rabbit.eats, it’s not in rabbit, so JavaScript follows the [[Prototype]] reference and finds it in animal.

If we have a method in animal, it can be called on rabbit.

For example,


let animal = {
    eats: true,
    walk() {
    alert("Animal walk");
    }
};

let rabbit = {
    jumps: true,
    __proto__: animal
};

// output
// walk is taken from the prototype
rabbit.walk(); // Animal walk

The method is automatically taken from the prototype.

The prototype Attribute

💡 Every object has associated prototype, class, and extensible attributes.

An object’s prototype attribute specifies the object from which it inherits properties.

💡 The prototype attribute is set when an object is created.

Objects created from object literals use Object.prototype as their prototype.

Objects created with new use the value of the prototype property of their constructor function as their prototype.

And objects created with Object.create() use the first argument to that function (which may be null) as their prototype.

Function prototypes

Functions have a prototype property distinct from their __proto__ property. It’s an object. A function’s prototype’s __proto__ property is equal to Object.prototype.

For example,


function fn() {}
console.log(fn.prototype.__proto__ === Object.prototype);
// -> true

The __proto__ of an object created by calling a function with new is equal to the prototype of that function.

The __proto__ of a function’s prototype is equal to Object.prototype. The __proto__ of Object.prototype is null

For example,


function Fn() {}
var obj = new Fn();
console.log(obj.__proto__ === Fn.prototype);
// -> true
console.log(obj.__proto__.__proto__=== Object.prototype);
// -> true
console.log(obj.__proto__.__proto__.__proto__ === null);

//something like This
__proto__ === null
|
|             
__proto__ === Object.prototype
|
|
__proto__ === Fn.prototype
|
|
obj

this keyword on the object’s prototype chain

If the method is on an object’s prototype chain, this refers to the object the method was called on, as if the method were on the object.


var o = {f: function() { return this.a + this.b; }};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5

In the example above, the object assigned to the variable p doesn’t have its own f property, it inherits it from its prototype.

The lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p.

That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript’s prototype inheritance.

Sources


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to Draw a Text Image using JavaScript?JavaScriptHow to remove a specific item from an array in JavaScript?JavaScriptHow to create a sticky menu pin using CSS?CSSHow to Install Xcode Command Line Tools on MacOS?MiscellaneousIntroduction to Angular modules Part 3: NgModules vs JavaScript modules and Angular librariesAngularHow to use @each rule with key-value pair in SCSS?SCSS