Understanding and Implementing Object-Oriented Programming with Classes
Classes in JavaScript provide a more structured way to create objects and implement inheritance. They were introduced in ECMAScript 2015 (ES6) and offer a cleaner syntax for object-oriented programming.
Use the class keyword to declare a class.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
const john = new Person('John', 30);
john.greet(); // Output: Hello, my name is John and I'm 30 years old.
The constructor method is a special method for creating and initializing objects created with a class.
You can define methods within the class body. These become part of the prototype of the class.
Use the extends keyword to create a class that is a child of another class.
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
console.log(`${this.name} is studying.`);
}
}
const alice = new Student('Alice', 20, 'A');
alice.greet(); // Output: Hello, my name is Alice and I'm 20 years old.
alice.study(); // Output: Alice is studying.
Classes support getter and setter methods, which allow you to define how a property is accessed or modified.
class Circle {
constructor(radius) {
this._radius = radius;
}
get radius() {
return this._radius;
}
set radius(value) {
if (value > 0) {
this._radius = value;
}
}
}
const circle = new Circle(5);
console.log(circle.radius); // Output: 5
circle.radius = 10;
console.log(circle.radius); // Output: 10
Private fields in JavaScript classes are denoted by a hash (#) prefix. They can only be accessed within the class itself.
class BankAccount {
#balance = 0;
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // Output: 150
// console.log(account.#balance); // This would throw an error
Inheritance allows a class to inherit properties and methods from another class. Polymorphism enables objects of different classes to be treated as objects of a common base class.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const animal = new Animal("Generic Animal");
const dog = new Dog("Buddy");
animal.speak(); // Output: Generic Animal makes a sound.
dog.speak(); // Output: Buddy barks.