Careeroza
Classes vs Prototypes
Classes Are Syntax Over Prototypes
Example
A class creates the same prototype structure as a constructor function:
class Dog {
constructor(name) { this.name = name; }
bark() { return this.name + " says woof"; }
}
class Puppy extends Dog {}
const d = new Puppy("Bruno");
console.log(typeof Dog);
console.log(Object.getPrototypeOf(d) === Puppy.prototype);
console.log(Object.getPrototypeOf(Puppy.prototype) === Dog.prototype);
console.log(d.bark());Output
function true true Bruno says woof
Composition over Inheritance
Example
Deep inheritance trees become rigid. Often it is simpler to combine small behaviours:
const canFly = (o) => ({ ...o, fly: () => o.name + " flies" });
const canSwim = (o) => ({ ...o, swim: () => o.name + " swims" });
const duck = canSwim(canFly({ name: "Duck" }));
console.log(duck.fly(), "|", duck.swim());Output
Duck flies | Duck swims