JavaScript Classes
14 April 2025 | Category: JavaScript
In JavaScript, classes provide a cleaner and more structured way to create objects and deal with inheritance. While JavaScript is prototype-based under the hood, classes make it easier to write object-oriented code.
đ What is a Class?
A class is a blueprint for creating objects. It defines properties (data) and methods (functions) that the objects created from the class will have.
đ§ Declaring a Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, Iâm ${this.name} and Iâm ${this.age} years old.`);
}
}
constructor()
is a special method that gets called when you create a new object from the class.
đ§Ş Creating an Object (Instance)
const john = new Person("John", 25);
john.greet(); // Output: Hi, Iâm John and Iâm 25 years old.
đ§Ź Inheritance (Extending Classes)
You can create a child class that inherits properties and methods from a parent class using extends
.
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // Call parent constructor
this.grade = grade;
}
study() {
console.log(`${this.name} is studying in grade ${this.grade}.`);
}
}
const dev = new Student("Dev", 20, 12);
dev.greet(); // Inherited method
dev.study(); // New method
đŚ Class Methods and Getters
You can add:
- Regular methods
- Getters and setters for controlled access to properties
class Product {
constructor(name, price) {
this.name = name;
this._price = price;
}
get price() {
return `$${this._price}`;
}
set price(value) {
if (value < 0) throw new Error("Price can't be negative");
this._price = value;
}
}
const item = new Product("Perfume", 120);
console.log(item.price); // $120
item.price = 140;
console.log(item.price); // $140
đ ď¸ Static Methods
Static methods belong to the class itself, not to any instance:
class MathUtil {
static square(n) {
return n * n;
}
}
console.log(MathUtil.square(5)); // 25
â Summary
Feature | Description |
---|---|
class | Defines a blueprint for objects |
constructor() | Initializes object properties |
extends | Inherits from another class |
super() | Calls the constructor of the parent class |
static | Method available on the class, not on instances |
get / set | Create custom getters and setters |
JavaScript classes are just syntactic sugar over its existing prototype-based inheritance system. They make code more readable and easier to maintain.