Hone

Lessons · JavaScript · prototypes under the hood

A class is a prototype with nicer syntax

Methods written in a class body live once, on Dog.prototype; each object holds only its own fields and finds methods by walking the prototype chain.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

This is why a thousand Dogs do not carry a thousand copies of bark, why instanceof works, and why an old codebase full of Dog.prototype.bark = function () {} is the same thing you write today with class.

How to think about it

Ask: is this data (goes on the object, in the constructor) or behaviour (goes on the prototype, as a method)? When something is 'missing', check the chain: Object.getPrototypeOf(obj).

Worked example

class Dog {
  constructor(name) { this.name = name; }
Data: on each object.
  bark() { return 'Woof'; }
Behaviour: on Dog.prototype, once.
}
const d = new Dog('Rex');
console.log(Object.getPrototypeOf(d) === Dog.prototype);
true
console.log(d.hasOwnProperty('name'), d.hasOwnProperty('bark'));
true false
console.log(JSON.stringify(Object.keys(d)));
["name"]

Your turn

Check where the method lives.

const proto = Object.(d);
console.log(proto === Dog.prototype);

The trap

Expecting Object.keys(d) or JSON.stringify(d) to include methods. They list own fields only; the methods sit on the prototype and are not copied.

Practise prototypes under the hood on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.