Welcome, JavaScript adventurers! In this chapter, we embark on a journey into the realm of object-oriented programming (OOP) using JavaScript classes. Classes provide a structured way to create objects with shared properties and behaviors, fostering code reusability and maintainability. Buckle up as we explore the fundamentals, practical applications, and advanced techniques of JavaScript classes.
class Car {
// Class properties (using the constructor)
constructor(model, year) {
this.model = model;
this.year = year;
}
// Class methods (functions)
greet() {
console.log("Hello from your", this.year, this.model + "!");
}
}
// Creating object instances (instances of the Car class)
const car1 = new Car("Honda Civic", 2023);
const car2 = new Car("Toyota Camry", 2022);
car1.greet(); // Output: Hello from your 2023 Honda Civic!
car2.greet(); // Output: Hello from your 2022 Toyota Camry!
Car class defines two properties (model and year) using the constructor method. The constructor is a special method that gets called whenever a new object (instance) is created from the class.greet method is a function defined within the class to log a greeting message.new keyword to create instances (car1 and car2) of the Car class, providing arguments for the constructor (model and year).car1.greet() and car2.greet(), the greet method is invoked on each object instance, printing the personalized greeting messages.Inheritance allows us to create new classes (subclasses) that inherit properties and methods from an existing class (superclass). This promotes code reusability and reduces redundancy
class ElectricCar extends Car {
constructor(model, year, batteryRange) {
super(model, year); // Call the superclass constructor
this.batteryRange = batteryRange;
}
greet() {
super.greet(); // Call the superclass greet method
console.log("...with a range of", this.batteryRange, "miles!");
}
}
const electricCar = new ElectricCar("Tesla Model S", 2024, 350);
electricCar.greet(); // Output: Hello from your 2024 Tesla Model S! ...with a range of 350 miles!
ElectricCar class inherits from the Car class using the extends keyword.ElectricCar constructor calls the superclass (Car) constructor using super(model, year) to initialize the inherited properties.greet method in ElectricCar overrides the superclass method. It first calls the superclass greet using super.greet() to print the base greeting, then adds its own message about the battery range.electricCar instance, and its greet method demonstrates the inheritance hierarchy.this).
class Person {
#name; // Private property (using # symbol)
constructor(name) {
this.#name = name;
}
getName() { // Public method to access private property
return this.#name;
}
static greetAll() {
console.log("Hello from everyone!");
}
}
const person1 = new Person("Alice");
console.log(person1.getName()); // Output: Alice (public method accesses private property)
# symbol to define a private property (#name). Private properties are only accessible from within the class using this.getName method provides a public way to access the private #name property.static methods are defined using the static keyword. They are associated with the class itself, not the object instances. We can call them using the class name directly (e.g., Person.greetAll()).Getters and Setters: These are special methods that allow us to control how properties are accessed and modified.
class Circle {
constructor(radius) {
this._radius = radius; // Private property with underscore prefix (convention)
}
get area() { // Getter for the calculated area
return Math.PI * this._radius * this._radius;
}
set radius(value) { // Setter to validate and assign radius
if (value <= 0) {
throw new Error("Radius cannot be negative or zero!");
}
this._radius = value;
}
}
const circle = new Circle(5);
console.log(circle.area); // Output: 78.53981633974483 (getter is called)
circle.radius = -10; // Throws an error (setter validates input)
_radius) with an underscore prefix (a convention for private properties in JavaScript).area getter calculates and returns the circle’s area using the private _radius.radius setter validates the input value before assigning it to the private property. It throws an error if the radius is negative or zero.
const Point = class {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `Point(${this.x}, ${this.y})`;
}
};
const point = new Point(3, 4);
console.log(point.toString()); // Output: Point(3, 4)
const Point = class { ... }.By understanding classes, inheritance, property access levels, and advanced features like getters, setters, and class expressions, you gain the power to structure your JavaScript code effectively. Classes promote code reusability, maintainability, and readability, making your applications more organized and easier to manage as they grow in complexity. Happy coding !❤️
