ES6 Classes
ES6 Classes provide a cleaner, more familiar syntax for creating objects and implementing inheritance in JavaScript, built on top of prototypes.
š¤ What are ES6 Classes?
ES6 Classes are syntactic sugar over JavaScript's existing prototype-based inheritance. They provide a clearer and more familiar syntax for OOP programming.
- Syntactic Sugar - Built on prototypes
- Constructor Method - Called when creating instances
- Instance Methods - Methods on prototype
- Static Methods - Methods on class itself
š” Class Features
constructor()- Initialization methodextends- Inheritance between classessuper()- Call parent constructor/methodsstatic- Static methods and propertiesget/set- Getter and setter methods- Private fields/methods (ES2022)
Under the Hood
Classes are still prototype-based. class Person creates a function Person with methods on its prototype.
š Class Basics
Basic class syntax with constructors, methods, getters, setters, and statics.
Key Components:
- Constructor - Initializes object properties
- Instance Methods - Available on all instances
- Getters/Setters - Computed properties
- Static Methods - Called on class, not instances
- Static Properties - Shared across all instances
𧬠Class Inheritance
Creating class hierarchies with extends and super.
Inheritance Rules:
- Use
extendsto inherit from another class - Must call
super()in derived class constructor - Can override parent methods
- Can call parent methods with
super.methodName() - Supports multiple levels of inheritance
š Private Fields & Methods
ES2022 private fields and methods for encapsulation.
Private Features:
#fieldName- Private field#methodName()- Private methodstatic #field- Static private field- Only accessible within class
Benefits:
- True encapsulation
- Prevents external modification
- Clear public API
- Better code organization
š§© Mixins & Composition
Using mixins and composition as alternatives to deep inheritance hierarchies.
Composition over Inheritance:
- Mixins - Functions that return classes
- Object Composition - Combine objects
- Traits - Reusable behaviors
- Advantages - More flexible, avoids deep hierarchies
š Practical Example: E-commerce
Complete e-commerce system demonstrating classes, inheritance, and encapsulation.
š” Class Design Best Practices:
- Single responsibility per class
- Use private fields for encapsulation
- Prefer composition over deep inheritance
- Use getters/setters for computed properties
- Add validation in setters
- Use static methods for utility functions
- Document public API with JSDoc
Next Steps
Now that you understand ES6 classes, learn about JavaScript's underlying prototype system that powers class inheritance.