JavaScript supports Object-Oriented Programming (OOP) using classes. Classes allow you to create objects, define methods, and implement inheritance, making code more organized and reusable.
This blog explains classes, objects, and OOP concepts with examples.
⭐ 1. What Is a Class?
A class is a blueprint for creating objects with properties and methods.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
let person1 = new Person("Sagar", 22);
person1.greet(); // Hello, my name is Sagar
⭐ 2. Class Methods
Class methods are functions defined inside a class.
class Calculator {
add(a, b) { return a + b; }
subtract(a, b) { return a - b; }
}
let calc = new Calculator();
console.log(calc.add(5, 3)); // 8
console.log(calc.subtract(5, 3)); // 2
⭐ 3. Getters and Setters
Getters and setters allow controlled access to object properties.
class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
get name() { return this._name; }
set age(newAge) { this._age = newAge; }
}
let person = new Person("Sagar", 22);
console.log(person.name); // Sagar
person.age = 23;
⭐ 4. Inheritance
Inheritance allows a class to extend another class, reusing its properties and methods.
class Animal {
speak() { console.log("Animal sound"); }
}
class Dog extends Animal {
speak() { console.log("Bark!"); }
}
let dog = new Dog();
dog.speak(); // Bark!
⭐ 5. Static Methods
Static methods belong to the class, not instances.
class MathUtils {
static square(x) { return x * x; }
}
console.log(MathUtils.square(5)); // 25
⭐ 6. Why Use Classes & OOP
- Organize code efficiently
- Reuse code with inheritance
- Encapsulate properties and methods
- Create modular and scalable applications
⭐ Conclusion
JavaScript classes enable object-oriented programming, making it easier to create reusable, modular, and maintainable code. Understanding classes, methods, inheritance, and encapsulation is key for advanced JavaScript development.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/