Skip to content
Related Articles
Open in App
Not now

Related Articles

How to use Class in Node.js ?

Improve Article
Save Article
Like Article
  • Last Updated : 01 Jul, 2020
Improve Article
Save Article
Like Article

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




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

Output:

Example 2: Class Expression




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());

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
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!