Introduced in ES6, the class keyword provides a clean syntactic sugar over JavaScript's existing prototype-based inheritance model. ES2022 added support for private fields (#field) and static class blocks.
flowchart TD
ParentClass["Base Class (Vehicle)"] --> ChildClass["Derived Class (Car) extends Vehicle"]
ChildClass --> SuperCall["constructor() calls super(brand)"]
ChildClass --> Instances["Instances (myCar) access instance & parent methods"]
| Feature | Syntax | Explanation |
|---|---|---|
| Constructor | constructor(props) {} |
Special initialization method invoked on new Class(). |
| Private Field | #privateSecret = 10; |
Hard private field accessible only within class body. |
| Static Method | static help() {} |
Utility method attached to Class constructor, not instances. |
| Getter / Setter | get score() {} / set score(v) {} |
Intercepts property reading and writing. |
| Inheritance | class Car extends Vehicle |
Establishes prototype inheritance chain. |
// Demonstrating ES6 Classes, Private Fields, and Inheritance
class User {
// Private field declaration (ES2022)
#passwordHash;
constructor(username, password) {
this.username = username;
this.#passwordHash = this.#hashPassword(password);
}
// Private method
#hashPassword(pass) {
return `HASHED_${pass}_SECURE`;
}
// Getter method
get userDetails() {
return `User: ${this.username}`;
}
// Instance method
validatePassword(inputPassword) {
return this.#passwordHash === this.#hashPassword(inputPassword);
}
// Static Utility Method
static compareUsers(userA, userB) {
return userA.username.localeCompare(userB.username);
}
}
// Subclass Inheritance
class AdminUser extends User {
constructor(username, password, role) {
super(username, password); // Must invoke super() before using 'this'
this.role = role;
}
getAdminInfo() {
return `${this.userDetails} [Role: ${this.role}]`;
}
}
const admin = new AdminUser("maksudur_dev", "secret123", "SuperAdmin");
console.log(admin.getAdminInfo());
console.log(`Password Valid? ${admin.validatePassword("secret123")}`);
super() First in Derived Constructors: In child class constructors extending a parent class, you MUST call super() before accessing this.#field) Are Enforced at Runtime: Private fields prefixed with # cannot be accessed or inspected from outside the class instance.new.Write a class Rectangle with width and height properties and a getter area returning width * height.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.