BFE.dev solution for Interview Question
2. What is Prototypal Inheritance? How does it work?
Let's forget about JavaScript, but just look at following class syntax in some unknown language.
class Animal { walk() { //... }}const dog = new Animal()const cat = new Animal()
We put things in a class because walk
is same for all animals.
Regarding the language itself, it is obviously more efficient for
these 2 instances share the method walk
, rather than each of them copying it.
So conceptually there should be a shared method bag that all instances share access to.
Now let's look at inheritance.
class Animal { walk() { //... }}class Dog extends Animal { bark() { // ... }}class Cat extends Animal { meow() { // ... }}const dog = new Dog()const cat = new Cat()dog.walk()
Here we have 3 shared property bags, for each of the classes. How
do we know that dog.walk
should trigger the function in Animal
?
We can of course just copy the method references from Animal
to
the shared property bag of Dog
and Cat
, but it will be a lot of
copying, what if there are updates on Animal
?
Let's go back to JavaScript.
Since JavaScript is such a dynamic
programming language, Animal
could have more properties on
the fly, rather than copying properties around, it could
be easier to just somehow connect the shared property bags so
that if a property is not in the shared property bag of Dog
,
its super class's shared property bag could be checked.
Let's give them some fancier names.
- shared property bag => prototype
- connected shared property bags => prototype chain
Conceptually there should be some mechanism similar to prototype in other languages as well such as C++ and Java, though they are implemented differently. But I'm no an expert on them so I'll leave it to you to figure it out.
From now on I hope it'll be much easier for you to understand what prototypal inheritance is and how it works.
1. Every object has an internal reference to its prototype.
We access its prototype by Object.getPrototypeOf()
(or __proto__
),
it should be another object or null
.
Also Object.create()
could be used to create an object from a prototype,
and we can alter the prototype dynamically by Object.setPrototypeOf()
.
2. Properties are looked up in the prototype chain.
When a property is accessed on an object, JavaScript checks if
the object has the property first. If not found then its prototype
is checked. This process continues until the property is found or
the chain ends with null
.
3. It is actually conceptually similar to class-based inheritance.
This could be debatable.
But the core idea is that they are similar conceptually but different
in implementation due to capabilities and philosophy of the language itself.
Anyway, class
keyword is supported since ES6, and it is quite similar syntax
to other languages as well.