Topic 31 of 37
ES6 Class Syntax
Overview
Introduced in ES6, the 'class' keyword is primarily syntactic sugar over JavaScript's existing prototype-based inheritance. It provides a much cleaner, Java-like syntax for creating blueprints for objects.
Syntax
Methods inside a class are automatically added to the prototype. The constructor is called when using the 'new' keyword.
Class Declaration & Private Fields
javascript
class User {
// Private field (starts with #)
#password;
constructor(name, password) {
this.name = name;
this.#password = password; // Set in constructor
}
// Getter method
get info() {
return `User: ${this.name}`;
}
// Method (stored on User.prototype)
checkPassword(attempt) {
return this.#password === attempt;
}
}
const u1 = new User("Alice", "secret");
console.log(u1.info); // "User: Alice"
// console.log(u1.#password); // SyntaxError: Private field!Common Pitfalls
- Losing 'this' context when passing a class method as a callback (e.g., in a setTimeout or React event handler). You must bind it or use an arrow function.
Interview Tips
- Make sure you know that classes are NOT hoisted like function declarations. You cannot instantiate a class before it is defined in the file.
Real-World Example
Creating custom error classes for better error handling.
example
javascript
class DatabaseError extends Error {
constructor(message, query) {
super(message);
this.name = "DatabaseError";
this.query = query;
}
}
throw new DatabaseError("Connection failed", "SELECT *");