About Lesson
Real-World Example: User Class
Consider an application where we manage user profiles. We can create a User class with properties like name, email, and role, and methods to update the user’s email or promote their role.
JavaScript
class User {
constructor(name, email, role = "user") {
this.name = name;
this.email = email;
this.role = role;
}
updateEmail(newEmail) {
this.email = newEmail;
console.log(`Email updated to: ${this.email}`);
}
promote() {
this.role = "admin";
console.log(`${this.name} is now an ${this.role}.`);
}
}
// Creating User instances
const user1 = new User("Alice", "alice@example.com");
const user2 = new User("Bob", "bob@example.com", "moderator");
user1.updateEmail("alice.new@example.com"); // Output: Email updated to: alice.new@example.com
user2.promote(); // Output: Bob is now an admin.
In this example:
- Each User object represents an individual user with properties name, email, and role.
- The updateEmail and promote methods allow modifying user data.