Category(s)
Topic(s)
JavaScript classes provide a structured way to define objects using a blueprint. They use the class
keyword and support features like constructors, methods, inheritance, and static properties.
Syntax
class ClassName {
constructor(parameters) {
// Initialize properties
}
methodName() {
// Define methods
}
}
Example
//Creating a Simple Class
class Person {
constructor(name, age) {
this.name = name; // Property
this.age = age; // Property
}
introduce() { // Method
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
}
}
// Creating an instance of the class
const person1 = new Person("Alice", 30);
person1.introduce(); // Output: Hi, I'm Alice and I'm 30 years old.
constructor()
: This is a special method that initializes the properties when an object is created.- Methods (
introduce()
): Functions inside a class that define behaviors.
Class Inheritance (Extending a Class)
Inheritance allows a class to inherit properties and methods from another class using extends.
Example
// Base Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
}
}
// Extending Person Class
class Employee extends Person {
constructor(name, age, jobTitle) {
super(name, age); // Calls the Person constructor
this.jobTitle = jobTitle;
}
work() {
console.log(`${this.name} works as a ${this.jobTitle}.`);
}
}
// Creating an instance of Employee
const emp1 = new Employee("Bob", 25, "Software Engineer");
emp1.introduce(); // Output: Hi, I'm Bob and I'm 25 years old.
emp1.work(); // Output: Bob works as a Software Engineer.
extends
: Allows a class to inherit from another.super()
: Calls the parent class's constructor.
Static Methods & Properties
Static methods and properties belong to the class itself, not to instances.
Example
// Using Static Methods
class MathUtils {
static add(a, b) {
return a + b;
}
}
// Calling the static method
console.log(MathUtils.add(5, 3)); // Outputs: 8
static
: Defines methods or properties that can be accessed without creating an instance.
Getters and Setters
Getters and setters allow controlled access to class properties.
Example
// Using Getters & Setters
class Circle {
constructor(radius) {
this._radius = radius; // Using `_` to indicate private property
}
get radius() {
return this._radius;
}
set radius(value) {
if (value > 0) {
this._radius = value;
} else {
console.log("Radius must be positive.");
}
}
}
const c = new Circle(10);
console.log(c.radius); // 10
c.radius = -5; // Error: Radius must be positive.
get
: Retrieves a property.set
: Allows controlled modification of a property.