WPDD

WordPress Develop & Design

Classes

ES6 introduces a class syntax to create objects and handle inheritance.

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const person1 = new Person("John", "Doe");
console.log(person1.getFullName()); // "John Doe"

Inheritance Example:

class Employee extends Person {
  constructor(firstName, lastName, role) {
    super(firstName, lastName); // Call the parent class constructor
    this.role = role;
  }

  getDetails() {
    return `${this.getFullName()} works as a ${this.role}`;
  }
}

const employee1 = new Employee("Jane", "Doe", "Developer");
console.log(employee1.getDetails()); // "Jane Doe works as a Developer"