JavaScript path · Foundations · Topic 4 of 12

Prototypes and classes

Not started

Every object has a hidden link to a prototype object. When a property isn't found on the object, the engine follows that link, and the next one, until it finds it or reaches null. class syntax is a tidier way to set up these links: methods live once on the prototype and every instance shares them.

Why it matters: It is how inheritance, instanceof and built-in methods like array.map actually work.

1

How it works

The explanation, with examples you can run.

Following the chain

Reading d.speak first looks at d itself, then at Dog.prototype, then at Animal.prototype, then at Object.prototype, and stops at null. Writing d.speak = ... never changes the prototype: it creates an own property on d that hides the shared one.

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Classes are prototypes with better manners

A class is still a function with a prototype object; extends links one prototype to another, and super looks up the chain from there. What classes add is safety and clarity: they must be called with new, their bodies are strict, and private fields (#secret) are truly private, which no prototype trick could do before.

The same mechanism serves built-ins: [1, 2].map is found on Array.prototype. You can create an object with any prototype directly with Object.create(proto), and Object.create(null) gives an object with no prototype at all, handy for plain lookup tables.

2

Check yourself

2 questions. Get them all right to finish this topic.

  1. 1.Where does the speak method of `class Dog { speak() {} }` live?
  2. 2.What does `x instanceof Animal` check?

0 of 2 right so far. Get all two to finish this topic.