Lessons in this course (16)

7. Prototypes, inheritance and classes

Intermediate★ Must knowLesson 7 of 16

Every object has an internal link [[Prototype]] (accessible via Object.getPrototypeOf(obj) or __proto__). Property lookup walks the prototype chain until found or null.

js
function Person(name) { this.name = name; }
Person.prototype.hello = function () { return `I am ${this.name}`; };
const p = new Person("Asha");
p.hello();                                   // found on Person.prototype

// ES6 classes — syntax over prototypes
class Animal {
  #sound;                                    // private field (ES2022)
  static count = 0;
  constructor(name, sound) { this.name = name; this.#sound = sound; Animal.count++; }
  speak() { return `${this.name} says ${this.#sound}`; }
  get label() { return this.name.toUpperCase(); }
}
class Dog extends Animal {
  constructor(name) { super(name, "woof"); }
  speak() { return super.speak() + "!"; }
}
new Dog("Rex").speak();                      // "Rex says woof!"

What new does: creates an empty object, sets its prototype to Constructor.prototype, calls the constructor with this = the object, returns the object (unless the constructor returns another object).