Saturday, March 30, 2024

What are classes in Javascript and explain Inheritance?

A JavaScript class is not an object. It is a template for JavaScript objects. Use the keyword class to create a class. 

Always add a method named constructor().

class Employee {

  constructor(name, department) {

    this.name = name;

    this.department = department;

  }

}

The example above creates a class named "Employee".

The class has two initial properties: "name" and "department".

The example below uses the Employee class to create a Employee object.

const myEmp = new Employee("Farukh", IT);

The constructor method is called automatically when a new object is created. The constructor method is a special method.

It has to have the exact name "constructor".

Sample Example to demonstrate class use:

class Employee {

  constructor(name, department) {

    this.name = name;

    this.department = department;

  }

  displayValue() {

    console.log('Name is '+this.name);

    console.log('department is '+this.department);

  }

}

const myEmp = new Employee("Farukh", "IT");

myEmp.displayValue();

Output:

Name is Farukh

department is IT

Class Inheritance:

To create a class inheritance, use the extends keyword.

A class created with a class inheritance inherits all the methods from another class:

class Employee {

  constructor(name, department) {

    this.name = name;

    this.department = department;

  }

}

class Manager extends Employee {

  constructor(name, department, position) {

    super(name, department);

    this.position = position;

  }

  displayValue() {

    console.log('Name is '+this.name);

    console.log('department is '+this.department);

    console.log('position is '+this.position);

  }

}

const myEmp = new Manager("Farukh", "IT", "Consultant");

myEmp.displayValue();

Output:

Name is Farukh

department is IT

position is Consultant

The super() method refers to the parent class.

By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods.

No comments:

Post a Comment