Prototype Chain
Every object has an internal [[Prototype]] link. When you access a property, JavaScript walks up the chain until it finds it or returns undefined.
const animal = { eats: true };
const rabbit = Object.create(animal);
rabbit.jumps = true;
console.log(rabbit.eats); // true — inherited from animal
Classes Are Syntactic Sugar
class User {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}`;
}
}
Under the hood, methods live on User.prototype.
Interview Questions
Q: Difference between proto and prototype?
prototypeexists on functions (used when called withnew)__proto__/Object.getPrototypeOfis the object's link to its prototype
Q: How does new work?
- Creates empty object
- Sets prototype to constructor.prototype
- Runs constructor with
thisbound to object - Returns object (unless constructor returns an object)
Q: Implement inheritance without class
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
return `${this.name} makes a sound`;
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;