Course outline · 0% complete

0/27 lessons0%

Course overview →

The prototype chain

lesson 3-1 · ~12 min · 6/27

Quiz

Warm-up from lesson 2-1: in `user.hello()`, what is `this` inside `hello`?

Every object has a hidden link

Every JavaScript object carries a hidden internal link called its prototype, pointing at another object (or at null). When you read a property, the lookup works like the scope chain from lesson 1-1, but for objects:

  1. Look on the object itself.
  2. Not there? Follow the prototype link and look on that object.
  3. Repeat until found, or until the chain ends at null (then you get undefined).

This path is the prototype chain. You can build it directly with Object.create(proto), which makes a new empty object whose prototype is proto.

Why the language works this way: sharing. A thousand user objects should not carry a thousand copies of the same methods, so JavaScript stores each method once on a shared object and lets lookup find it. It is also why [1, 2, 3].map(...) works at all — you never wrote map; the array's prototype supplies it.

Code exercise · javascript

Run it. `rex` has no `describe` of its own. The lookup follows the prototype link to `animal` and finds it there. Note `this` is still `rex`, because of how the method was called.

rexname, kindanimaldescribe()Object.prototypehasOwnProperty()looking for describe…lookup walks left to right until it finds the property or hits null
Property lookup walks the prototype chain: rex, then animal, then Object.prototype, then null.

Quiz

You run `rex.toString()`. rex has no `toString`, and neither does `animal`. What happens?

Writes do not climb the chain

The chain is for reads only. Assigning cat.sound = "meow" never modifies the prototype — it creates an own property on cat that shadows the inherited one (same word and same idea as variable shadowing in lesson 1-1). Delete the own property and the inherited value shows through again.

This asymmetry is deliberate: one instance changing a value must not silently change its siblings. Flip side: mutating the shared prototype object itself does affect every instance at once, which is a classic source of spooky bugs.

Code exercise · javascript

Run it. The first read climbs to `animal`. The write creates cat's OWN `sound`, shadowing the inherited one. Deleting the own property reveals the prototype's value again — `animal` was never touched.

Code exercise · javascript

Your turn. Create a `shape` prototype object with an `area()` method that returns `this.width * this.height`. Then use `Object.create` to make a `box` with width 4 and height 5, and print its area.