Mastering JavaScript Classes: A Comprehensive Guide.πππͺ
Dharmendra Kumar
Posted on June 14, 2024
Introduction
JavaScript classes, introduced in ECMAScript 2015 (ES6), provide a much cleaner and more intuitive syntax for creating objects and dealing with inheritance. This post explores JavaScript classes in depth, covering essential concepts and features with clear examples.
1. Overview
JavaScript classes are templates for creating objects. They encapsulate data with code to work on that data. Although they are primarily syntactical sugar over JavaScript's existing prototype-based inheritance, classes make object-oriented programming more accessible and easier to understand.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person1 = new Person('Alice', 30);
person1.greet(); // Hello, my name is Alice and I am 30 years old.
2. Constructor
The constructor
method is a special method for creating and initializing an object created with a class. There can be only one special method with the name "constructor" in a class.
Example:
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
displayInfo() {
console.log(`This car is a ${this.brand} ${this.model}.`);
}
}
const myCar = new Car('Toyota', 'Corolla');
myCar.displayInfo(); // This car is a Toyota Corolla.
3. Extends
The extends
keyword is used in class declarations or class expressions to create a class that is a child of another class.
Example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const myDog = new Dog('Rex');
myDog.speak(); // Rex barks.
4. Private Properties
Private properties are declared with a #
prefix, making them inaccessible from outside the class.
Example:
class User {
#password;
constructor(username, password) {
this.username = username;
this.#password = password;
}
checkPassword(password) {
return this.#password === password;
}
}
const user1 = new User('john_doe', '12345');
console.log(user1.checkPassword('12345')); // true
console.log(user1.#password); // SyntaxError: Private field '#password' must be declared in an enclosing class
5. Public Class Fields
Public class fields are properties that can be defined directly within the class body, making them more concise and readable.
Example:
class Product {
name = 'Default';
price = 0;
constructor(name, price) {
this.name = name;
this.price = price;
}
displayProduct() {
console.log(`Product: ${this.name}, Price: $${this.price}`);
}
}
const product1 = new Product('Laptop', 1200);
product1.displayProduct(); // Product: Laptop, Price: $1200
6. Static Methods
Static methods are called on the class itself, not on instances of the class. They are often used to create utility functions.
Example:
class MathUtils {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
}
console.log(MathUtils.add(5, 3)); // 8
console.log(MathUtils.subtract(5, 3)); // 2
7. Static Initialization Blocks
Static initialization blocks allow you to perform complex initialization of static properties.
Example:
class Config {
static API_URL;
static PORT;
static {
this.API_URL = 'https://api.example.com';
this.PORT = 8080;
}
static getConfig() {
return `API URL: ${this.API_URL}, PORT: ${this.PORT}`;
}
}
console.log(Config.getConfig()); // API URL: https://api.example.com, PORT: 8080
8. Getters and Setters
Getters and setters are used to define methods that get and set the value of an objectβs properties.
Example:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(name) {
[this.firstName, this.lastName] = name.split(' ');
}
}
const person = new Person('John', 'Doe');
console.log(person.fullName); // John Doe
person.fullName = 'Jane Smith';
console.log(person.fullName); // Jane Smith
9. Instance Methods
Instance methods are methods defined within a class that operate on instances of that class.
Example:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
perimeter() {
return 2 * (this.width + this.height);
}
}
const rectangle = new Rectangle(10, 5);
console.log(rectangle.area()); // 50
console.log(rectangle.perimeter()); // 30
Conclusion
JavaScript classes offer a clean and concise way to create and manage objects, providing a range of features to support object-oriented programming. By understanding constructors, inheritance, private properties, public fields, static methods, and other concepts, you can leverage the full power of JavaScript classes in your projects. Happy coding!
Posted on June 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.