Prototypes & Inheritance — JavaScript interview guide
Prototypes & Inheritance
Every object has a hidden link to another object called its prototype. If a property is missing, JS looks it up along this prototype chain. ES6 classes are built on top of this.
See it run
Press Play, or step with Next. Follow the arrows: anything that cannot be reached from a variable or root is free to go.
How JavaScript walks the prototype chain
1class Animal {2speak() { return "..."; }3}▶class Dog extends Animal {5bark() { return "woof"; }6}78const tom = new Dog();9console.log(tom.bark());10console.log(tom.speak());11console.log(tom.toString());12console.log(tom.fly());
What happens:Classes put their methods on a shared prototype object. Dog extends Animal links Dog.prototype → Animal.prototype → Object.prototype → null.
Explained simply
The prototype chain
obj.__proto__ (or Object.getPrototypeOf(obj)) points to the prototype. Arrays inherit from Array.prototype, which inherits from Object.prototype, which ends at null.
const arr = [1, 2];
arr.map; // found on Array.prototype
arr.hasOwnProperty; // found on Object.prototype
Object.getPrototypeOf(Array.prototype) === Object.prototype; // trueConstructor functions and classes
Methods placed on Fn.prototype are shared by all instances, instead of copied into each one. A class does the same thing with cleaner syntax.
class Animal {
constructor(name) { this.name = name; }
speak() { return this.name + " makes a sound"; }
}
class Dog extends Animal {
speak() { return super.speak() + " — woof"; }
}
new Dog("Tom").speak();
// Dog.prototype.__proto__ === Animal.prototype → trueRemember this
- prototype is a property of functions; __proto__ is the link on every object.
- Object.create(proto) makes an object with a chosen prototype.
- Classes are syntax sugar over prototypes.
Interview questions
Difference between prototype and __proto__?
Fn.prototype is the object that will become __proto__ of instances created with new Fn(). __proto__ is the actual link every object uses for lookup.
What does the new keyword do?
Creates an empty object, links its __proto__ to Fn.prototype, calls Fn with this set to that object, and returns it (unless Fn returns another object).
Practice
- Implement your own myNew(Fn, ...args).
- Add a method to Array.prototype and explain why it is a bad idea in real code.
Keep learning
More in Functions & Objects