Prototypes & Inheritance
Definition
Prototypes are the mechanism by which JavaScript objects inherit features from one another. Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain.
Explain Like I'm New
Imagine you have a basic recipe for a 'Cake'. This base recipe is the prototype. If you want to make a 'Chocolate Cake', you don't rewrite the whole recipe; you just say 'use the Cake recipe, but add chocolate'. The Chocolate Cake inherits the basic instructions from the Cake prototype.
Real World Example
When you create an array `let arr = []`, you can immediately use `arr.push()`. You didn't write the `push` function! Your array inherited it from the `Array.prototype` object built into JavaScript.
Common Use Cases
- •Sharing methods across multiple object instances to save memory
- •Implementing classical Object-Oriented patterns (Inheritance)
- •Extending built-in objects (though generally discouraged)
Interactive Example
Interview Questions
basic
- What is a prototype in JavaScript?
- How do you access an object's prototype?
intermediate
- What is the prototype chain?
- What is the difference between __proto__ and prototype?
advanced
- How does Object.create() work?
- What happens when a method is called that doesn't exist on the object itself?
trick
- What is the prototype of Object.prototype?