Explain how prototypal inheritance works in JavaScript
TL;DR
Prototypical inheritance in JavaScript is a way for objects to inherit properties and methods from other objects. Every JavaScript object has a special hidden property called [[Prototype]]
(commonly accessed via __proto__
or using Object.getPrototypeOf()
) that is a reference to another object, which is called the object's "prototype".
When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's __proto__
, and the __proto__
's __proto__
and so on, until it finds the property defined on one of the __proto__
s or until it reaches the end of the prototype chain.
This behavior simulates classical inheritance, but it is really more of delegation than inheritance.
Here's an example of prototypal inheritance:
Things to note are:
.makeSound
is not defined onDog
, so the JavaScript engine goes up the prototype chain and finds.makeSound
on the inheritedAnimal
.- Using
Object.create()
to build the inheritance chain is no longer recommended. UseObject.setPrototypeOf()
instead.
Prototypical Inheritance in Javascript
Prototypical inheritance is a feature in JavaScript used to create objects that inherit properties and methods from other objects. Instead of a class-based inheritance model, JavaScript uses a prototype-based model, where objects can directly inherit from other objects.
Key Concepts
- Prototypes : Every object in Javascript has a prototype, which is another object. When you create an object using an object literal or a constructor function, the new object is linked to the prototype of its constructor function or the
Object.prototype
if no prototype is specified. This is commonly referenced using__proto__
or[[Prototype]]
. You can also get the prototype by using inbuilt methodObject.getPrototypeOf()
and you can set the prototype of an object viaObject.setPrototypeOf()
.
-
Prototype chain: When a property or method is accessed on an object, JavaScript first looks for it on the object itself. If it doesn't find it there, it looks at the object's prototype, and then the prototype's prototype, and so on, until it either finds the property or reaches the end of the chain (i.e.,
null
). -
Constructor functions: JavaScript provides constructor functions to create objects. When a function is used as a constructor with the new keyword, the new object's prototype (
[[Prototype]]
) is set to the constructor's prototype property.
Object.create()
: This method creates a new object with the specified prototype object and properties. It's a straightforward way to set up prototypical inheritance. If you create a object viaObject.create(null)
it will not inherit any properties fromObject.prototype
. This means the object will not have any built-in properties or methods liketoString()
,hasOwnProperty()
,