JavaScript prototypes and class inheritance

Every JavaScript object has a hidden link to a prototype object. When a property is not found on the object itself, the engine looks it up along the chain of prototypes. A constructor function sets up new objects with this, and methods placed on Constructor.prototype are shared by all instances instead of being copied.

JavaScript
function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function () {
  return this.name + " makes a sound";
};

const rex = new Animal("Rex");
console.log(rex.speak(), Object.getPrototypeOf(rex) === Animal.prototype);

class Dog extends Animal {
  speak() {
    return super.speak() + " (woof)";
  }
}

const fido = new Dog("Fido");
console.log(fido.speak());
console.log(fido instanceof Dog, fido instanceof Animal, Object.hasOwn(fido, "speak"));
Read the full lesson