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:
- Class expressions
- 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.
Please Login to comment...