Classes in JavaScript
In JavaScript, a class is a blueprint for creating objects with shared properties and methods.
Classes provide a syntactic sugar over JavaScript’s prototype-based inheritance, making object-oriented programming easier and more readable.
- Introduced in ES6 (ECMAScript 2015).
- Classes are special functions internally, but allow a cleaner syntax.
- Support constructors, methods, inheritance, and static members.
Basic Syntax
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
// Creating an instance
const alice = new Person("Alice", 25);
alice.greet(); // Hello, my name is Alice
Inheritance
Classes can inherit properties and methods from another class using extends
.
super()
is used to call the parent class constructor.- Subclasses inherit all methods of the parent class.
class Employee extends Person {
constructor(name, age, job) {
super(name, age); // Call parent constructor
this.job = job;
}
work() {
console.log(`${this.name} is working as a ${this.job}`);
}
}
const bob = new Employee("Bob", 30, "Developer");
bob.greet(); // Hello, my name is Bob
bob.work(); // Bob is working as a Developer
Static Methods and Properties
Static members belong to the class itself, not instances.
- Cannot call static methods on instances:
new Calculator().add()
- Useful for utility functions related to the class.
class Calculator {
static add(a, b) {
return a + b;
}
}
console.log(Calculator.add(5, 3)); // 8
Getters and Setters
Classes can have getters and setters to control access to properties.
get
allows reading a computed property.set
allows updating a property with logic.
class Circle {
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
set diameter(value) {
this.radius = value / 2;
}
}
const c = new Circle(10);
console.log(c.area); // 314.159...
c.diameter = 20;
console.log(c.radius); // 10
Private & Public Fields
- Public fields are accessible outside the class.
- Private fields (ES2022+) are prefixed with
#
and only accessible inside the class.
class Counter {
#count = 0; // private
total = 0; // public
increment() { this.#count++; this.total++; }
getCount() { return this.#count; }
}
const c = new Counter();
c.increment();
console.log(c.total); // 1
console.log(c.getCount()); // 1
// console.log(c.#count); // Error: private field
Real-World Use Cases
- Modeling real-world entities: Users, Cars, Products.
- Organizing shared behavior across multiple objects.
- Implementing OOP patterns like inheritance, polymorphism, and encapsulation.
- Creating modules with static utility methods.