techStackGuru

JavaScript Classes


Class is a blueprint or prototype that contains all of the data (variables and methods)


Advantages of classes

  • Classes make it simple to maintain all of the data members and methods in one place.
  • A class specifies how and what an object will contain.
  • The class introduces the notion of data hiding (Encapsulation)
  • It also supports the idea of Inheritance. Obtaining the characteristics and methods that allow cod e to be reused.

We use class keyword to define a class

Syntax


class ClassName {
    constructor() { ... }
 } 

The class syntax is composed of two parts:

  • Class declarations
  • Class expressions

Lets take an example of class


class EmpInfo {
    constructor(empId, empName) {
      this.empId = empId;
      this.empName = empName;
    }
  }

Lets create an object to call class


const obj = new EmpInfo(1701, "Torgal");

All together


class EmpInfo {
    constructor(empId, empName) {
      this.empId = empId;
      this.empName = empName;
    }
  }
  
  const obj = new EmpInfo(1701, "Torgal");
  console.log(obj.empId +" "+obj.empName)
Output

1701 Torgal

previous-button
next-button