How to use Class in Node.js ?

Introduction: In the modern JavaScript, there is a more advanced “class” construct, that introduces great new features that are useful for object-oriented programming. As we can define a function in two way i.e. function expressions and function declarations.

The class syntax has two components:

  1. Class expressions
  2. Class declarations

Syntax:

// Class expression
let class_name  = class {
 constructor(method1, method2) {
    this.method1 = method1;
    this.method2= method2;
  }
};

// Class declaration
class class_name {
  constructor(method1, method2) {
    this.method1 = method1;
    this.method2= method2;
  }
}

Example 1: Class Declaration

filter_none

edit
close

play_arrow

link
brightness_4
code

class Polygon {
  constructor(height, width) {
    this.area = height * width;
  }
}
  
console.log(new Polygon(5, 15).area);

chevron_right


Output:



Example 2: Class Expression

filter_none

edit
close

play_arrow

link
brightness_4
code

const Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  
  area() {
    return this.height * this.width;
  }
};
  
console.log(new Rectangle(6, 10).area());

chevron_right


Output:

Class body and method definition: The body of a class is within the curly brackets {} and this is the place where you define class members such as methods or constructors. The constructor method is a special method for creating and initializing an object created with a class. A constructor can use the super keyword to call the constructor of the superclass.

My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.