Exploring modern class syntax and features.
The **`constructor`** is a special method for creating and initializing an object created with a class. The **`extends`** keyword is used in class declarations or class expressions to create a child class from a parent class.
class Animal { constructor(name) { this.name = name; } speak() { return `Hi, I'm ${this.name}.`; } } class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; } speak() { return `${super.speak()} and I'm a ${this.breed}.`; } }
Public class fields (`myField = value;`) are an easier way to define instance properties without using the constructor. **Private elements** (`#myField;`) provide true encapsulation, making the field inaccessible from outside the class.
class User { // Public class field country = 'USA'; // Private class field #password = 'secret123'; getPassword() { return this.#password; } }
`static` members belong to the class itself, not to any instance of the class. They are useful for utility functions or properties that don't depend on an object's state. **Static initialization blocks** provide a place to perform complex initialization for static properties.
class Counter { static count = 0; static { // A block to perform complex static setup console.log('Class initialized'); } static increment() { return ++this.count; } }