Lab 05: Prototype & Classes

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Overview

Master JavaScript's prototype chain, Object.create, modern class syntax with private fields, static methods, inheritance with extends/super, Symbol.iterator, and Mixin patterns.


Step 1: Prototype Chain

// Every object has a prototype (except Object.prototype)
const animal = {
  breathe() { return `${this.name} breathes`; },
  toString() { return `[Animal: ${this.name}]`; }
};

const dog = Object.create(animal);
dog.name = 'Rex';
dog.bark = function() { return `${this.name} barks!`; };

console.log(dog.breathe()); // Rex breathes (inherited)
console.log(dog.bark());    // Rex barks!
console.log(dog.toString()); // [Animal: Rex]
console.log(Object.getPrototypeOf(dog) === animal); // true

// Prototype chain lookup
console.log(dog.hasOwnProperty('name'));    // true (own property)
console.log(dog.hasOwnProperty('breathe')); // false (inherited)
console.log('breathe' in dog);              // true (searches chain)

// Viewing the chain
let obj = dog;
while (obj) {
  console.log(Object.getOwnPropertyNames(obj));
  obj = Object.getPrototypeOf(obj);
}

Step 2: Object.create and Prototypal Inheritance


Step 3: Class Syntax


Step 4: Private Fields & Methods


Step 5: Inheritance with extends/super


Step 6: Symbol.iterator


Step 7: Mixin Pattern


Step 8: Capstone — Animal Kingdom

Run verification:

📸 Verified Output:


Summary

Feature
Syntax
Notes

Prototype chain

Object.getPrototypeOf(obj)

Foundation of JS inheritance

Object.create

Object.create(proto)

Pure prototypal inheritance

Class fields

field = value

Public class fields

Private fields

#field

Truly private, not accessible outside

Static

static method()

Called on class, not instances

Inheritance

class B extends A

super() required in constructor

Symbol.iterator

[Symbol.iterator]()

Makes objects iterable

Mixins

(Base) => class extends Base

Composable behaviors

Last updated