Advanced · 6 of 11 · 17 min read
Prototype
The chain every object has, how a lookup walks it, and the difference between __proto__, prototype and Object.create.
- Prototypes
Every JavaScript object has a hidden link to another object, its prototype. When a property is
not found on an object, the engine follows that link and looks there, and so on until the link is
null. That walk is the whole inheritance model.
The lookup
const parent = { greet() { return 'hello'; } };
const child = Object.create(parent);
child.name = 'Ana';
console.log(child.name); // "Ana" — found on the object itself
console.log(child.greet()); // "hello" — not found, so one step up the chain
console.log(child.toString !== undefined); // true — two steps up, Object.prototype
console.log(child.nope); // undefined — the chain ended at null
The chain, written out:
console.log(Object.getPrototypeOf(child) === parent); // true
console.log(Object.getPrototypeOf(parent) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype)); // null — the end
Own property or inherited? Three tools, and the difference matters:
console.log(Object.hasOwn(child, 'name')); // true
console.log(Object.hasOwn(child, 'greet')); // false — inherited
console.log('greet' in child); // true — `in` walks the chain
console.log(Object.keys(child)); // ["name"] — own and enumerable only
for (const key in child) console.log(key); // "name" then "greet" — for...in walks up
prototype versus __proto__
The distinction the interview is actually testing:
function Dog(name) {
this.name = name;
}
Dog.prototype.speak = function () {
return `${this.name} barks`;
};
const rex = new Dog('Rex');
console.log(rex.speak()); // "Rex barks"
console.log(Object.getPrototypeOf(rex) === Dog.prototype); // true
console.log(rex.prototype); // undefined — instances have none
console.log(Dog.prototype.constructor === Dog); // true — the back-reference
| Expression | Belongs to | Is |
|---|---|---|
Dog.prototype |
the function Dog |
the object its instances inherit from |
rex.__proto__ |
the instance | the link to Dog.prototype |
Object.getPrototypeOf(rex) |
— | the same link, properly |
Dog.prototype.constructor |
the prototype | back to Dog |
__proto__ is a legacy accessor, standardised only for compatibility. Use
Object.getPrototypeOf / Object.setPrototypeOf, and Object.create when building.
What new does
Four steps, and knowing them makes the rest obvious:
function Dog(name) {
this.name = name;
}
Dog.prototype.speak = function () { return `${this.name} barks`; };
// `new Dog('Rex')` is equivalent to:
function construct(Fn, ...args) {
const obj = Object.create(Fn.prototype); // 1. new object, linked to Fn.prototype
const result = Fn.apply(obj, args); // 2. run Fn with `this` as that object
return typeof result === 'object' && result !== null ? result : obj; // 3./4.
}
const rex = construct(Dog, 'Rex');
console.log(rex.speak(), rex instanceof Dog); // "Rex barks" true
Step four is a real rule, not a footnote: a constructor that returns an object overrides the instance — which is how a factory can pretend to be a constructor.
function Weird() {
this.a = 1;
return { b: 2 }; // an object wins
}
console.log(new Weird()); // { b: 2 }
function Normal() {
this.a = 1;
return 42; // a primitive is ignored
}
console.log(new Normal()); // Normal { a: 1 }
The chain is live
Methods are looked up at call time, so an instance created before a prototype method sees it anyway:
function Cat(name) { this.name = name; }
const kitty = new Cat('Kitty');
// console.log(kitty.meow()); // TypeError: kitty.meow is not a function
Cat.prototype.meow = function () { return `${this.name} meows`; };
console.log(kitty.meow()); // "Kitty meows" — the existing instance found the new method
This is why prototype methods are shared rather than copied — one function object, however many instances:
const a = new Cat('A');
const b = new Cat('B');
console.log(a.meow === b.meow); // true — the same function
console.log(Object.hasOwn(a, 'meow')); // false
Shadowing
Assigning to a property always writes an own property. It never modifies the prototype:
const parent = { greeting: 'hello' };
const child = Object.create(parent);
console.log(child.greeting); // "hello" — inherited
child.greeting = 'hi'; // creates an own property
console.log(child.greeting, parent.greeting); // "hi" "hello"
console.log(Object.hasOwn(child, 'greeting')); // true
delete child.greeting; // remove the own one
console.log(child.greeting); // "hello" — the inherited one is visible again
The exception is a setter on the prototype, which does run:
const base = {
set value(v) { this._v = v * 2; },
get value() { return this._v; },
};
const derived = Object.create(base);
derived.value = 5; // the inherited setter ran
console.log(derived.value, Object.hasOwn(derived, '_v')); // 10 true
And the trap this creates with a shared mutable prototype property: reading reaches the prototype and mutating in place affects everybody, while assigning does not.
function Shared() {}
Shared.prototype.tags = [];
const one = new Shared();
const two = new Shared();
one.tags.push('x'); // mutating the shared array
console.log(two.tags); // ["x"] — the surprise
one.tags = ['own']; // assignment creates an own property
console.log(two.tags); // ["x"] — unaffected this time
Which is why arrays and objects belong on the instance, set in the constructor, and only functions belong on the prototype.
Object.create
Makes an object with the prototype you name — including none at all:
const proto = { describe() { return `I am ${this.name}`; } };
const made = Object.create(proto, {
name: { value: 'Ana', enumerable: true, writable: true },
});
console.log(made.describe()); // "I am Ana"
const bare = Object.create(null);
console.log(Object.getPrototypeOf(bare)); // null
bare.toString = 'just data'; // no collision — nothing was inherited
// console.log(`${bare}`); // TypeError: no toString to call
A prototype-less object is the right choice for a dictionary, precisely because it has no inherited keys to collide with your data:
const counts = {};
console.log('toString' in counts); // true — a false positive
const safe = Object.create(null);
console.log('toString' in safe); // false
console.log(Object.hasOwn(Object.prototype, 'toString')); // true — where it came from
Classes use the same machinery
A class is syntax over this model, nothing more:
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound`; }
}
const dog = new Animal('Rex');
console.log(Object.getPrototypeOf(dog) === Animal.prototype); // true
console.log(Object.getOwnPropertyNames(Animal.prototype)); // ["constructor", "speak"]
console.log(typeof Animal); // "function"
The one visible difference is enumerability — class methods are non-enumerable, so for...in and
Object.keys skip them:
function Old() {}
Old.prototype.m = function () {};
console.log(Object.keys(Old.prototype)); // ["m"]
class New { m() {} }
console.log(Object.keys(New.prototype)); // [] — non-enumerable
Built-in chains
console.log(Object.getPrototypeOf([]) === Array.prototype); // true
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype); // true
console.log(Object.getPrototypeOf(() => {}) === Function.prototype); // true
console.log(Object.getPrototypeOf(1) === Number.prototype); // true — boxed
Which explains how a primitive appears to have methods: 'abc'.toUpperCase() boxes the string,
finds the method on String.prototype, calls it and discards the wrapper.
Extending a built-in prototype is possible and almost always wrong:
// Array.prototype.last = function () { return this[this.length - 1]; };
// Now every for...in over any array in the program sees "last".
The reasons: it is global, it collides with future standards, and it breaks for...in. A plain
function, or a subclass, instead.
Common mistakes
Confusing prototype with __proto__
Mistake. Reaching for instance.prototype.
Why it fails. Only functions have prototype; instances have the hidden link.
What to do instead. Object.getPrototypeOf(instance), or Fn.prototype when you mean the
function’s.
Putting mutable state on a prototype
Mistake. Fn.prototype.items = [].
Why it fails. Every instance shares that one array, so a push from one appears in all of them.
What to do instead. Initialise per-instance state in the constructor, or as a class field.
Using Object.setPrototypeOf on a live object
Mistake. Re-pointing an object’s prototype after it has been used.
Why it fails. Engines deoptimise objects whose shape changes like this; MDN explicitly warns that
it is slow.
What to do instead. Create the object with the prototype it needs — Object.create, or a class.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
A method you can call is not necessarily a property the object owns.
What does this log?
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return "Hi " + this.name;
};
const p = new Person("Ana");
console.log(p.hasOwnProperty("greet"));There is a way to set an object’s prototype directly, with no constructor involved.
What does this log?
const base = { greet: () => "hi" };
const child = Object.create(base);
console.log(child.greet(), Object.keys(child).length);Why is adding a method to Array.prototype considered a bad idea?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.