[[Prototype]]speakfunctionnametoStringfunctionnullname1class Dog {2 constructor(name) { this.name = name; }3 speak() { return this.name + " woofs"; }4}5const rex = new Dog("Rex");6const fido = new Dog("Fido");7console.log(rex.speak());8console.log(rex.toString());9console.log(rex.fly);ConsoleRex woofsdogs.js:7[object Object]dogs.js:8undefineddogs.js:9"Rex""Fido"speaktoStringfly
Right: objects in memory (rex, fido, Dog.prototype, Object.prototype) and nullTraces: the hidden [[Prototype]] links; left: the script and the consoleTokens: instructions, values, and a property name searching up the chainOn the left, the script dogs.js and the developer console. On the right, the heap: null and Object.prototype at the back, Dog.prototype in the middle, and the two dogs, rex and fido, at the front. The traces between the objects are their hidden [[Prototype]] links. The class makes Dog.prototype; each new makes an object linked to it. To read a property, JavaScript looks on the object first, then follows the links one by one until it finds the property or reaches null. The hidden link is the internal slot [[Prototype]] in the ECMAScript specification. Read it with Object.getPrototypeOf(obj). Browsers also expose it as obj.__proto__, but that is a legacy accessor; prefer getPrototypeOf.

Prototypes

  1. Every object has a hidden link, called [[Prototype]], to another object or to null. Object.prototype is built in. It holds methods such as toString that ordinary objects share. Its own link is null: the end of the line.

Making objects with a class

Looking up a property

What happens

// step 1/10 · hidden-link
object        a bag of properties (name → value)
[[Prototype]] a hidden link to another object, or null
read it       Object.getPrototypeOf(obj)
built in      Object.prototype  (toString, valueOf, …)
              its [[Prototype]] is null

The hidden link is the internal slot [[Prototype]] in the ECMAScript specification. Read it with Object.getPrototypeOf(obj). Browsers also expose it as obj.__proto__, but that is a legacy accessor; prefer getPrototypeOf. The figure shows only the properties the example uses. Dog.prototype also has constructor, which points back to Dog, and Object.prototype has more methods, such as hasOwnProperty and valueOf.