The earlier Classes and OOP lesson used the class keyword — but underneath it, JavaScript objects don't use classes the way other languages do. They use prototypes, and class is really a friendlier syntax built on top of that older system.
An object's prototype is another object it automatically looks up properties and methods on, when it doesn't have one of its own.
const animal = {
eats: true,
}
const rabbit = Object.create(animal) // rabbit's prototype is animal
rabbit.jumps = true
console.log(rabbit.jumps) // true — rabbit's own property
console.log(rabbit.eats) // true — found on animal, its prototypeIf a property isn't found on the prototype either, JavaScript keeps looking up the prototype's own prototype, and so on, until it reaches null — this chain is why it's called prototypal inheritance.
function Dog(name) {
this.name = name
}
Dog.prototype.bark = function () {
console.log(`${this.name} says woof!`)
}
const rex = new Dog('Rex')
rex.bark() // "Rex says woof!" — found on Dog.prototype, not on rex itselfA class method is stored on the prototype exactly the same way — class doesn't replace the prototype system, it's a more readable way to write to it.
class Dog {
constructor(name) {
this.name = name
}
bark() {
console.log(`${this.name} says woof!`)
}
}
// Behind the scenes, bark() lives on Dog.prototype — same as before
console.log(typeof Dog.prototype.bark) // "function"Why methods live on the prototype, not each object
Every object created from a class or constructor function shares one copy of each method on the prototype — this is why methods (unlike properties set in the constructor) don't take extra memory per object.