What is class in JavaScript full explain?

Asked 19-Jul-2021
Viewed 208 times

1 Answer


1

Class and Object is a very important part for OOP. The concept of OOP is dependent on Objects and Classes. There can be many member functions and data members inside the class. Which is accessed through the object. Class is like a structure. In which variable(data members) and function(member functions) are write at one place. Data member and member functions are the members of the class. Works to hold class data. Class This is the layout of the object.

Syntax

 class class-name [ extends other class] {
  //public or private fields
  // constructor
  //get and set property
//function
 }

Class declarations

we are declaring a class using the class keyword with the name of the class  'Rectangle' in JavaScript. 

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width; }

Class expressions

A class expression is another way to declare a class. Class expressions can be named or unnamed class declarations. This class will access by temporary name.

temporary_name.function-name()  and temporary_name.fields-name

// unnamed class 

let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

Constructor

Constructor is a special method for creating and initializing a variable created with a class in JavaScript. There is only one constructor method in JavaScript, A SyntaxError will be throw if the class contains more than one constructor method. A constructor can use the super keyword to call the constructor of the superclass.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter property
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}
const square = new Rectangle(10, 10);
console.log(square.area); // 100

Field declarations

Public field declarations

class Rectangle {
  height = 0;
 width;
  constructor(height, width) {     this.height = height;
    this.width = width;
  }
}

Private field declarations

class Rectangle {
  #height = 0;
  #width;
  constructor(height, width) {
    this.#height = height;
    this.#width = width;
  }
}

Extends the superclass

The extends keyword is used in class to create a class as a child of a parent class.

//Parent Class declaration
class Animal {   constructor(name) {     this.name = name;   }   speak() {     console.log(`${this.name} makes a noise.`);   } }

//Child Class declaration

class Dog extends Animal {   constructor(name) {     super(name); // call the super class constructor and pass in the name parameter   }   speak() {     console.log(`${this.name} barks.`);   } } let d = new Dog('Mitzie'); d.speak(); // Mitzie barks.