Lab 05: Classes & OOP

🎯 Objective

Use ES6 classes, inheritance, static methods, private fields, and getter/setter to write clean object-oriented JavaScript.

📚 Background

JavaScript's class syntax (ES6+) is syntactic sugar over prototype chains. Classes provide a familiar OOP interface while JavaScript's prototype system works underneath. ES2022 added private class fields (#field) for true encapsulation without closures. Understanding prototype-based inheritance helps debug class-related bugs.

⏱️ Estimated Time

35 minutes

📋 Prerequisites

  • Lab 4: Arrays & Objects

🛠️ Tools Used

  • Node.js 20

🔬 Lab Instructions

Step 1: Basic Class

📸 Verified Output:

Step 2: Inheritance

📸 Verified Output:

Step 3: Static Methods and Properties

📸 Verified Output:

Step 4: Getters, Setters, and Validation

📸 Verified Output:

Step 5: Mixins (Multiple Inheritance Pattern)

📸 Verified Output:

Step 6: Iterator Protocol

📸 Verified Output:

Step 7: Abstract Base Pattern

📸 Verified Output:

Step 8: Design Pattern — Observer

📸 Verified Output:

✅ Verification

Expected output:

🚨 Common Mistakes

  1. Forgetting super() in constructors: Derived class constructors must call super() before accessing this.

  2. this in regular method callbacks: arr.forEach(function() { this.x })this is undefined; use arrow functions.

  3. Public vs private: this._name (underscore) is convention only — not truly private. Use #name for real privacy.

  4. instanceof across realms: Fails across iframes/workers — use duck typing or Symbol.hasInstance.

  5. Static and instance confusion: this.staticMethod() doesn't work; call ClassName.staticMethod().

📝 Summary

  • class Name { constructor() {} method() {} get prop() {} } — ES6 class syntax

  • extends for inheritance; always super() before this in child constructor

  • #field for true private fields (ES2022); static for class-level members

  • Mixins: const Mix = (Base) => class extends Base {} for multiple inheritance

  • [Symbol.iterator]() makes objects iterable with for...of and spread

  • Design patterns: Observer/EventEmitter, Abstract Base, Factory, Builder

🔗 Further Reading

Last updated