Prototypes & Inheritance
What is a Prototype?
JavaScript is a prototype-based language. All JavaScript objects inherit properties and methods from a prototype.
Dateobjects inherit fromDate.prototypeArrayobjects inherit fromArray.prototypePersonobjects inherit fromPerson.prototype
The Prototype Chain
When you try to access a property of an object:
- JavaScript first checks if the object itself has the property.
- If not, it looks at the object's prototype.
- If not there, it looks at the prototype's prototype.
- This continues until it reaches
Object.prototype(the top of the chain).
Adding Properties to Prototypes
You can add new properties or methods to all existing objects of a given type by adding them to the prototype.
Array.prototype) as this can cause
conflicts with other libraries.
Prototypal Inheritance
Before ES6 Classes, prototypes were the primary way to implement inheritance in JavaScript.
Summary
- Every JavaScript object has a prototype.
- Objects inherit properties and methods from their prototype.
- The prototype chain allows for property lookups up the hierarchy.
- You can extend constructors by adding to their
.prototype.
Quick Quiz
What is the top of the prototype chain?
Enjoying these tutorials?