Javascript Fundamentals · Interview Fundamentals

Prototypes

the prototype chain

Prototypes

const animal = {
  speak() {
    return 'generic sound';
  },
};
const dog = Object.create(animal);
dog.speak(); // 'generic sound' — found on the prototype

dog has no speak of its own, yet the call works. Every object carries a hidden link to another object, and when you read a property that is not on the object itself, JavaScript follows that link — and then the next one — until it finds the property or reaches null. That chain is the prototype chain.

Functions get a prototype property, and objects made with new Fn() set their prototype to Fn.prototype. That is how methods are shared instead of copied onto every instance.

function Dog(name) {
  this.name = name;
}
Dog.prototype.speak = function () {
  return `${this.name} barks`;
};

Object.getPrototypeOf(obj) reads the link; obj.hasOwnProperty(key) tells you whether a property is the object's own rather than inherited. Almost everything ultimately inherits from Object.prototype, which is why toString works on nearly every value.

You are about to answer a short quiz on the prototype chain.

  1. Every object has a hidden link to another object called its prototype.
  2. When a property is missing, JavaScript looks it up along the ___ chain.
  3. Objects created with new Fn() have Fn.prototype as their prototype.
  4. Object.___(obj) returns an object's prototype.
  5. obj.hasOwnProperty(key) reports whether a property is the object's own rather than inherited.
  6. Methods are shared through the prototype instead of being ___ onto every instance.
  7. The prototype chain ends at null.