Sikau

Advanced JavaScript · Day 6 · about 25 min

Prototypes

How objects share methods behind the scenes.

Where do methods come from?

Every array has .map, every string has .toUpperCase — but you never wrote those onto your arrays. They live on a shared object called a prototype. When JavaScript can't find a property on an object, it looks up the chain.

The prototype chain

const animal = {
  speak() {
    return this.name + " makes a sound";
  },
};

const dog = Object.create(animal);
dog.name = "Kale";

console.log(dog.speak());
console.log(Object.hasOwn(dog, "speak"));
console.log(Object.getPrototypeOf(dog) === animal);

Asking the family: If you don't know a recipe, you ask your mother; if she doesn't know, she asks hers. Property lookup walks up the family tree the same way, until it finds the answer or runs out of ancestors (null).

const list = [3, 1, 2];
console.log(Object.getPrototypeOf(list) === Array.prototype);
console.log(Object.hasOwn(Array.prototype, "map"));

console.log(Object.keys({ a: 1 }));
console.log("a" in { a: 1 }, "toString" in { a: 1 });

The rest of this lesson

  • Prototypes and classesexplain
  • Predict the outputpredict
  • Own or inherited?predict
  • Property lookuporder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript