Clean β’ Professional
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.
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
Classes can inherit properties and methods from another class using extends.
super() is used to call the parent class constructor.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 members belong to the class itself, not instances.
new Calculator().add()class Calculator {
static add(a, b) {
return a + b;
}
}
console.log(Calculator.add(5, 3)); // 8
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
# 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