Questions
What is the prototype chain and how does it work in JavaScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new feature that needs to create a new object that inherits properties from another object.
You are not sure whether to use classical inheritance or prototypal inheritance.
The Challenge
Explain what the prototype chain is in JavaScript and how it works. What are the pros and cons of prototypal inheritance, and how does it compare to classical inheritance?
A junior engineer might not be aware of the prototype chain. They might try to solve this problem by using classical inheritance, which is not the standard way to do inheritance in JavaScript.
A senior engineer would have a deep understanding of the prototype chain. They would be able to explain what it is and how it works. They would also be able to explain the pros and cons of prototypal inheritance and would have a clear recommendation for which one to use in this use case.
Step 1: Understand What the Prototype Chain Is
The prototype chain is a mechanism in JavaScript that allows an object to inherit properties from another object.
Every object in JavaScript has a prototype. When you try to access a property on an object, JavaScript will first look for the property on the object itself. If it does not find the property on the object, it will look for the property on the object’s prototype. If it does not find the property on the prototype, it will look for the property on the prototype’s prototype, and so on, until it reaches the end of the prototype chain.
Step 2: How to Create a Prototype Chain
Here’s how we can create a simple prototype chain:
const animal = {
isAlive: true
};
const dog = {
bark() {
console.log('woof');
}
};
Object.setPrototypeOf(dog, animal);
console.log(dog.isAlive); // true
dog.bark(); // woofIn this example, we use the Object.setPrototypeOf() method to set the prototype of the dog object to the animal object.
Prototypal Inheritance vs. Classical Inheritance
| Feature | Prototypal Inheritance | Classical Inheritance |
|---|---|---|
| Inheritance | Objects inherit from other objects. | Classes inherit from other classes. |
| Flexibility | More flexible, you can add or remove properties from an object at runtime. | Less flexible, you cannot add or remove properties from a class at runtime. |
| Complexity | Simpler and more intuitive. | More complex and verbose. |
When to use Prototypal Inheritance
You should almost always use prototypal inheritance in JavaScript. It is the standard way to do inheritance in JavaScript, and it is more flexible and less complex than classical inheritance.
Practice Question
You want to create a new object that inherits from another object. Which of the following would you use?