×

javascript · level 3 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Methods live on a that every instance shares.

Classes are a friendlier way to write something older: prototypes. Methods are not copied into each instance. They live once on the class's prototype object, and every instance links to it. A thousand orders share one total method.

When you read rex.speak, JavaScript looks on rex first. Missing? It follows the link to the prototype, then to that prototype's prototype. This is the . walks the same chain to ask: was this object built by that class, or by a child of it?

class Animal { speak() { return "Hello"; } }
class Dog extends Animal { fetchBall() { return "Got it!"; } }
const rex = new Dog();
console.log(Object.getPrototypeOf(rex) === Dog.prototype);
console.log(rex.speak === new Animal().speak);
console.log(Object.hasOwn(rex, "speak"));
console.log(rex instanceof Dog, rex instanceof Animal, rex instanceof Array);

Object.getPrototypeOf(x) shows the object x falls back on, and Object.hasOwn(x, key) asks whether x holds key itself.