CodeBlanks Logo Icon CodeBlanks

Summary - Prototypes

JavaScript course · Advanced · Lesson 18/100

Build an animal inheritance structure using Object.create and the prototype chain.

Summary - Prototypes

In this group you learned prototypes. Every object links to a prototype; you read it with Object.getPrototypeOf, and build new objects with Object.create. The prototype chain carries property lookups upward; hasOwnProperty filters own properties.

Now we combine these into an animal inheritance structure: animalProto as the base, dogProto as the layer above it, rex as the concrete object.

Exercise Build the animal inheritance chain

Define animalProto with a describe method that returns 'I am an animal'. Create dogProto with Object.create(animalProto) and add a dogProto.bark function returning 'woof'. Create rex with Object.create(dogProto); then set rex.name = 'Rex' as its own property. Loop rex's keys with for...in; when rex.hasOwnProperty(key) is true, call console.log(key). Finally call console.log(rex.describe()), console.log(rex.bark()) and console.log(Object.getPrototypeOf(rex) === dogProto).

Show example solution
const animalProto = {
  describe() {
    return 'I am an animal';
  }
};
const dogProto = Object.create(animalProto);
dogProto.bark = function () {
  return 'woof';
};
const rex = Object.create(dogProto);
rex.name = 'Rex';
for (const key in rex) {
  if (rex.hasOwnProperty(key)) {
    console.log(key);
  }
}
console.log(rex.describe());
console.log(rex.bark());
console.log(Object.getPrototypeOf(rex) === dogProto);

Final notes

Prototypes are JavaScript's inheritance mechanism. Even though class syntax is common in new code, prototypes still run underneath. Building chains with Object.create, filtering with hasOwnProperty, and reading with Object.getPrototypeOf are safe habits.

Avoid mutating the prototype directly (for example Object.prototype.x = ...); it affects every object and leads to surprising behavior.

Test yourself

  1. Which method creates a new object with a given prototype?

    • Object.create(proto)
    • Object.getPrototypeOf(proto)
    • Object.keys(proto)
    • Object.setPrototypeOf(proto)
    Show answer

    Object.create(proto) — Correct! Object.create does exactly this.

  2. Create dogProto with Object.create

    const dogProto = Object.____;
    Show answer
    const dogProto = Object.create(animalProto);
  3. Match all prototype concepts

    Object.create
    new object + prototype
    Object.getPrototypeOf
    prototype read
    hasOwnProperty
    own property check
    prototype chain
    lookup path

All lessons in Advanced