Prototypal Inheritance

Prototypal Inheritance is an object getting access to the properties and methods of another object. So, Array [] object gets access to properties and methods of the object in JavaScript. And the same with functions through the chain that we call prototypal Inheritance.

* Array [] gets access to the methods and properties of object.

* Function {} gets access to the methods and properties of object.

const array = [1];
console.log(array);
console.log(array.__proto__);
console.log(array.__proto__.__proto__);
console.log(array.__proto__.__proto__.__proto__);
console.log(array.toString());
[ 1 ]
[]
{}
null
1

array.__proto__.__proto__ is object {}.

const fun = function () { return 1 };
console.log(fun);
console.log(fun.__proto__);
console.log(fun.__proto__.__proto__);
console.log(fun.__proto__.__proto__.__proto__);
console.log(fun.toString());
[Function: fun]
[Function]
{}
null
function() {return 1}

fun.__proto__.__proto__ is object {}.

const obj = { "1": 1 };
console.log(obj);
console.log(obj.__proto__);
console.log(obj.__proto__.__proto__);
console.log(obj.toString());
{ '1': 1 }
{}
null
[object Object]

obj.__proto__ is object {}.

This feature is actually quite unique and not that common in other popular languages like C# and Java. They use something called classical inheritance.

There is no classes in JavaScript. JavaScript only have prototypal inheritance.

__proto__

let a ={
    blog: "a note"
}

let b = {
    post: 3
}

b.__proto__ =a;
console.log(b.blog)
a note

Through the prototype chain all the properties and methods of the object a and overwritten anything that we have already declared in our own object b.

Check prototype Chain

let a ={
    blog: "a note"
}

let b = {
    post: 3
}

b.__proto__ =a;

console.log(b.blog)

for (let prop in b){
    if(b.hasOwnProperty(prop)){
        console.log(prop);
    }
}
a note
post

It seems pretty useful but you never use it. It is bad for performance and there is a different way that we can inherit it comes to prototype.

Thus, How to create our own prototype?

let human = {
    mortal: true
}
let socrates = Object.create(human)
socrates.quotation = "One thing only I know, and that is that I know nothing.";
console.log(socrates);
console.log(socrates.mortal)
console.log(socrates.__proto__);
{
  quotation: 'One thing only I know, and that is that I know nothing.'
}
true
{ mortal: true }
  • __proto__ : Never use for performance reason in JavaScript.
  • __proto__ : always points to prototype.

Everything in JavaScript is an Object. arrays and functions also are objects they inherit through the prototype chain from the base object.

Leave a Reply

Your email address will not be published.

ANOTE.DEV