JavaScript Prototypal Inheritance
In JavaScript, prototypal inheritance allows objects to inherit properties and methods from another object. This is one of JavaScript’s core features and is used to share behavior efficiently.
š¹ What is Prototype?
Every JavaScript object has an internal property called [[Prototype]]
, which points to another object (its prototype). If a property is not found in an object, JavaScript looks up the prototype chain until it finds the property or reaches null
.
✔ Object.create(person)
creates a new object that inherits from person
.
š¹ The __proto__
Property
We can manually set or access an object’s prototype using __proto__
.
✔ rabbit
does not have eats
, so JavaScript looks up the prototype (animal
) to find it.
š¹ Prototype Chain Lookup
JavaScript continues searching up the prototype chain if a property/method isn’t found in an object.
✔ JavaScript follows the prototype chain until it finds the property/method or reaches null
.
š¹ Using Object.create()
for Inheritance
A cleaner way to create objects with a prototype is using Object.create()
.
✔ Object.create(prototypeObj)
creates an object that inherits from prototypeObj
.
š¹ Constructor Functions & Prototypes
A constructor function automatically sets the prototype of its instances.
✔ Methods added to Person.prototype
are shared across all instances.
š¹ class
Syntax and extends
The modern way to use inheritance in JavaScript is with ES6 classes.
✔ extends
creates a prototype chain automatically.
✔ super
allows calling methods from the parent class.
šÆ Summary
✔ Every object in JavaScript has a prototype.
✔ Properties/methods are inherited through the prototype chain.
✔ Use Object.create()
for inheritance.
✔ Constructor functions inherit via Function.prototype
.
✔ Modern JavaScript uses class
and extends
for inheritance.
š Prototypal inheritance is a powerful concept in JavaScript! Let me know if you need more details. š