Classes (ES6)

Program demonstrating ES6 classes

JavaScriptIntermediate
JavaScript
// Class declaration
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    greet() {
        return `Hello, I'm ${this.name}`;
    }
    
    getAge() {
        return this.age;
    }
}

let person1 = new Person("Alice", 25);
console.log(person1.greet());
console.log("Age:", person1.getAge());

// Class with inheritance
class Student extends Person {
    constructor(name, age, grade) {
        super(name, age);  // Call parent constructor
        this.grade = grade;
    }
    
    study() {
        return `${this.name} is studying`;
    }
    
    // Override parent method
    greet() {
        return `Hi, I'm ${this.name}, a student`;
    }
}

let student1 = new Student("Bob", 20, "A");
console.log("\nStudent:");
console.log(student1.greet());
console.log(student1.study());
console.log("Grade:", student1.grade);

// Static methods
class MathUtils {
    static add(a, b) {
        return a + b;
    }
    
    static multiply(a, b) {
        return a * b;
    }
}

console.log("\nStatic methods:");
console.log("Add:", MathUtils.add(5, 3));
console.log("Multiply:", MathUtils.multiply(5, 3));

// Getters and Setters
class Circle {
    constructor(radius) {
        this._radius = radius;
    }
    
    get radius() {
        return this._radius;
    }
    
    set radius(value) {
        if (value > 0) {
            this._radius = value;
        } else {
            throw new Error("Radius must be positive");
        }
    }
    
    get area() {
        return Math.PI * this._radius ** 2;
    }
}

let circle = new Circle(5);
console.log("\nCircle:");
console.log("Radius:", circle.radius);
console.log("Area:", circle.area.toFixed(2));
circle.radius = 10;
console.log("New radius:", circle.radius);
console.log("New area:", circle.area.toFixed(2));

Output

Hello, I'm Alice
Age: 25

Student:
Hi, I'm Bob, a student
Bob is studying
Grade: A

Static methods:
Add: 8
Multiply: 15

Circle:
Radius: 5
Area: 78.54
New radius: 10
New area: 314.16

This program demonstrates ES6 classes in JavaScript.

Class Declaration

Modern syntax for object-oriented programming:

javascript
class ClassName {
    constructor(parameters) {
        // Initialize
    }
    
    method() {
        // Method
    }
}

Constructor

Special method called when object is created:

javascript
constructor(name, age) {
    this.name = name;
    this.age = age;
}

Inheritance

Extend parent class:

javascript
class Child extends Parent {
    constructor(params) {
        super(params);  // Call parent constructor
    }
}

super keyword:

  • Calls parent constructor
  • Accesses parent methods
  • Required in child constructor

Method Overriding

Child can override parent methods:

javascript
class Child extends Parent {
    method() {
        // Override parent method
    }
}

Static Methods

Belong to class, not instance:

javascript
class Utils {
    static method() {
        // Called on class, not instance
    }
}
Utils.method();  // Not instance.method()

Getters and Setters

Control property access:

javascript
get property() {
    return this._property;
}

set property(value) {
    // Validation
    this._property = value;
}

Benefits:

  • Validation
  • Computed properties
  • Encapsulation

Class vs Constructor Function:

FeatureClassConstructor
SyntaxModernTraditional
HoistingNoYes
Strict modeAlwaysOptional
InheritanceextendsManual

When to Use:

  • Class: Modern OOP, inheritance

  • Constructor: Legacy code, simple objects