We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Prototypal Inheritance

Click to play video

So... I tricked you a bit. Classes are actually a fairly new addition to JavaScript. See, they're not the underlying mechanism for inheritance - that's actually prototypes. Classes are just syntactic sugar for prototypes.

Every object in JavaScript has a prototype. When an object "inherits" from another object, it's really that its parent is marked as its "prototype". It's called prototypal inheritance. The built-in Object.create() method creates a new object with its prototype set to the given object.

const pureTitan = {
  // (define a parent object / prototype)
  name: "Eren's mom",
  speak(msg) {
    console.log("*titan noises*");
  },
};
pureTitan.speak();
// *titan noises*

const beastTitan = Object.create(pureTitan); // (define a child)

console.log(beastTitan.name); // (accessing .name from pureTitan)
// Eren's mom

beastTitan.name = "Zeke";
beastTitan.speak = function () {
  console.log(`${this.name} says, "I'm the Beast Titan"`);
};

beastTitan.speak();
// Zeke says, "I'm the Beast Titan"

Assignment

Textio needs a new notification system that uses a new subclass of notification that can both:

  • send to a single user (regular notifications already do this)
  • broadcast messages to all users (specific to this new subclass)
Broadcast to all users: MESSAGE_GOES_HERE

Where "MESSAGE_GOES_HERE" is the given message string.