Day 14: JavaScript Classes
Screenshot:-
JavaScript classes provide a way to create objects and manage inheritance, encapsulation, and code reuse. This guide will take you through defining classes, using inheritance, static methods and properties, getters and setters, and private fields. By the end of these activities, you’ll have a solid understanding of how to work with classes in JavaScript.
Table of Contents
Class Definition
Class Inheritance
Static Methods and Properties
Getters and Setters
Private Fields
1. Class Definition
Classes in JavaScript are templates for creating objects. They encapsulate data with code to work on that data.
Task 1: Define a Person Class
Define a Person
class with properties name
and age
, and a method to return a greeting message:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
const person1 = new Person('John', 25);
console.log(person1.greet());
Task 2: Add a Method to Update Age
Add a method to the Person
class to update the age
property and log the updated age:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
updateAge(newAge) {
this.age = newAge;
console.log(`Updated age: ${this.age}`);
}
}
const person1 = new Person('John', 25);
person1.updateAge(26);
2. Class Inheritance
Inheritance allows a class to inherit properties and methods from another class.
Task 3: Define a Student Class that Extends Person
Define a Student
class that extends the Person
class and adds a studentId
property and a method to return the student ID:
class Student extends Person {
constructor(name, age, studentId) {
super(name, age);
this.studentId = studentId;
}
getStudentId() {
return `Student ID: ${this.studentId}`;
}
}
const student1 = new Student('Alice', 20, 'S12345');
console.log(student1.getStudentId());
Task 4: Override the Greeting Method
Override the greet
method in the Student
class to include the student ID in the message:
class Student extends Person {
constructor(name, age, studentId) {
super(name, age);
this.studentId = studentId;
}
greet() {
return `Hello, my name is ${this.name}, I am ${this.age} years old, and my student ID is ${this.studentId}.`;
}
}
const student1 = new Student('Alice', 20, 'S12345');
console.log(student1.greet());
3. Static Methods and Properties
Static methods and properties belong to the class itself rather than to instances of the class.
Task 5: Add a Static Method to the Person Class
Add a static method to the Person
class that returns a generic greeting message:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
static genericGreet() {
return 'Hello, this is a generic greeting message.';
}
}
console.log(Person.genericGreet());
Task 6: Add a Static Property to the Student Class
Add a static property to the Student
class to keep track of the number of students created, and increment this property in the constructor:
class Student extends Person {
static count = 0;
constructor(name, age, studentId) {
super(name, age);
this.studentId = studentId;
Student.count++;
}
greet() {
return `Hello, my name is ${this.name}, I am ${this.age} years old, and my student ID is ${this.studentId}.`;
}
static getStudentCount() {
return `Total number of students: ${Student.count}`;
}
}
const student1 = new Student('Alice', 20, 'S12345');
const student2 = new Student('Bob', 22, 'S67890');
console.log(Student.getStudentCount());
4. Getters and Setters
Getters and setters allow you to define methods that get and set the value of an object’s properties.
Task 7: Add a Getter Method to the Person Class
Add a getter method to the Person
class to return the full name:
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const person1 = new Person('John', 'Doe', 25);
console.log(person1.fullName);
Task 8: Add a Setter Method to the Person Class
Add a setter method to the Person
class to update the name properties:
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(name) {
const [firstName, lastName] = name.split(' ');
this.firstName = firstName;
this.lastName = lastName;
}
}
const person1 = new Person('John', 'Doe', 25);
person1.fullName = 'Jane Smith';
console.log(person1.fullName);
5. Private Fields
Private fields ensure that properties are only accessible within the class.
Task 9: Define a Class with Private Fields
Define a class Account
with private fields for balance and methods to deposit and withdraw money:
class Account {
#balance = 0;
#accountNumber;
#accountHolderName;
constructor(accountNumber, accountHolderName) {
this.#accountNumber = accountNumber;
this.#accountHolderName = accountHolderName;
}
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
console.log(`Deposited: ${amount}`);
} else {
console.log('Deposit amount must be positive');
}
}
withdraw(amount) {
if (amount > 0 && amount <= this.#balance) {
this.#balance -= amount;
console.log(`Withdrew: ${amount}`);
} else {
console.log('Insufficient balance or invalid amount');
}
}
getBalance() {
return this.#balance;
}
getAccountDetails() {
return {
accountNumber: this.#accountNumber,
accountHolderName: this.#accountHolderName,
balance: this.#balance
};
}
}
const myAccount = new Account('1234567890', 'John Doe');
myAccount.deposit(100);
myAccount.withdraw(50);
console.log(`Balance: ${myAccount.getBalance()}`);
console.log(myAccount.getAccountDetails());
Conclusion and Additional Resources
By mastering classes, you can write cleaner, more modular JavaScript code. Classes help organize your code, making it easier to maintain and reuse. For further reading, check out these resources:
JavaScript.info: Classes
Eloquent JavaScript: Classes
Subscribe to my newsletter
Read articles from Alpit Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Alpit Kumar
Alpit Kumar
I am a passionate web developer and open-source enthusiast on a captivating journey of coding wonders. With a year of experience in web development, my curiosity led me to the enchanting world of React, where I found a true calling. Embracing the magic of collaboration and knowledge-sharing, I ventured into the realm of open source, contributing to Digital Public Goods (DPGs) for the betterment of the digital universe. A firm believer in learning in public, I share my insights and discoveries through blogging, inspiring fellow coders to embark on their own magical coding odysseys. Join me on this thrilling adventure, where imagination and technology converge, and together, let's shape the future of the digital landscape! 🎩✨