In this chapter, we will learn about JavaScript classes and objects. Classes are blueprints for creating objects, and objects are instances of classes. We will cover:
- What are Classes?
- Creating Classes
- Constructor Method
- Creating Objects
- Adding Methods to a Class
- Accessing Object Properties and Methods
- Modifying Object Properties
- Static Methods
- Getters and Setters
- Simple Programs using Classes and Objects
What are Classes?
Classes are templates for creating objects. They encapsulate data with code to work on that data. In JavaScript, classes were introduced in ES6 (ECMAScript 2015) as a new syntax for creating objects and dealing with inheritance.
Creating Classes
You can create a class using the class
keyword followed by the class name and a block containing the constructor and methods.
Syntax
class ClassName { constructor(parameters) { // Initialize properties } // Methods }
Example
class Person { constructor(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } }
Constructor Method
The constructor
method is a special method for creating and initializing objects created with a class. It is called automatically when a new object is instantiated.
Example
class Person { constructor(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } }
Creating Objects
You can create objects from a class using the new
keyword.
Example
let person1 = new Person("Ramesh", "Fadatare", 25); let person2 = new Person("Neha", "Sharma", 30); console.log(person1); console.log(person2);
Output:
Person { firstName: 'Ramesh', lastName: 'Fadatare', age: 25 } Person { firstName: 'Neha', lastName: 'Sharma', age: 30 }
Adding Methods to a Class
Methods can be added to a class to define behaviors for the objects.
Example
class Person { constructor(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } // Method to get full name getFullName() { return `${this.firstName} ${this.lastName}`; } } let person = new Person("Ramesh", "Fadatare", 25); console.log(person.getFullName());
Output:
Ramesh Fadatare
Accessing Object Properties and Methods
You can access object properties and methods using dot notation.
Example
class Car { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } displayInfo() { return `${this.make} ${this.model} (${this.year})`; } } let car = new Car("Maruti", "Swift", 2021); console.log(car.make); console.log(car.displayInfo());
Output:
Maruti Maruti Swift (2021)
Modifying Object Properties
You can modify object properties by assigning a new value to the property.
Example
let car = new Car("Maruti", "Swift", 2021); car.year = 2022; console.log(car.year);
Output:
2022
Static Methods
Static methods are defined on the class itself, not on the objects created from the class. They are called on the class, not on instances of the class.
Example
class MathUtil { static add(a, b) { return a + b; } } console.log(MathUtil.add(5, 3));
Output:
8
Getters and Setters
Getters and setters allow you to define methods that are executed when a property is accessed or modified.
Example
class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } get fullName() { return `${this.firstName} ${this.lastName}`; } set fullName(name) { let parts = name.split(' '); this.firstName = parts[0]; this.lastName = parts[1]; } } let person = new Person("Ramesh", "Fadatare"); console.log(person.fullName); person.fullName = "Neha Sharma"; console.log(person.firstName); console.log(person.lastName);
Output:
Ramesh Fadatare Neha Sharma
Simple Programs using Classes and Objects
Program 1: Bank Account
class BankAccount { constructor(accountNumber, accountHolder, balance) { this.accountNumber = accountNumber; this.accountHolder = accountHolder; this.balance = balance; } deposit(amount) { this.balance += amount; } withdraw(amount) { if (amount > this.balance) { console.log("Insufficient funds"); } else { this.balance -= amount; } } getBalance() { return this.balance; } } let account = new BankAccount("1234567890", "Rahul Sharma", 5000); account.deposit(2000); account.withdraw(1000); console.log("Balance:", account.getBalance());
Output:
Balance: 6000
Program 2: Library Management
class Book { constructor(title, author, isbn) { this.title = title; this.author = author; this.isbn = isbn; } getDetails() { return `${this.title} by ${this.author}, ISBN: ${this.isbn}`; } } class Library { constructor() { this.books = []; } addBook(book) { this.books.push(book); } removeBook(isbn) { this.books = this.books.filter(book => book.isbn !== isbn); } getBooks() { return this.books.map(book => book.getDetails()); } } let library = new Library(); let book1 = new Book("The Alchemist", "Paulo Coelho", "123456"); let book2 = new Book("The Monk Who Sold His Ferrari", "Robin Sharma", "789101"); library.addBook(book1); library.addBook(book2); library.removeBook("123456"); console.log(library.getBooks());
Output:
["The Monk Who Sold His Ferrari by Robin Sharma, ISBN: 789101"]
Program 3: Employee Management
class Employee { constructor(name, position, salary) { this.name = name; this.position = position; this.salary = salary; } getDetails() { return `${this.name}, ${this.position}, Salary: ${this.salary}`; } } class Manager extends Employee { constructor(name, position, salary, department) { super(name, position, salary); this.department = department; } getDetails() { return `${super.getDetails()}, Department: ${this.department}`; } } let emp1 = new Employee("Ramesh Fadatare", "Developer", 50000); let emp2 = new Manager("Neha Sharma", "Manager", 80000, "IT"); console.log(emp1.getDetails()); console.log(emp2.getDetails());
Output:
Ramesh Fadatare, Developer, Salary: 50000 Neha Sharma, Manager, Salary: 80000, Department: IT
Conclusion
In this chapter, you learned about JavaScript classes and objects, including creating classes and objects, adding methods, accessing and modifying properties, static methods, and getters and setters. We also provided various use cases with simple programs to demonstrate the usage of classes and objects. Classes and objects are fundamental in JavaScript for organizing and managing your code.