1// Improved formatting of Spotted Tailed Quoll's answer
2class Person {
3 constructor(name, age) {
4 this.name = name;
5 this.age = age;
6 }
7 introduction() {
8 return `My name is ${name} and I am ${age} years old!`;
9 }
10}
11
12let john = new Person("John Smith", 18);
13console.log(john.introduction());
1class Rectangle {
2 constructor(height, width) {
3 this.height = height;
4 this.width = width;
5 }
6 // Getter
7 get area() {
8 return this.calcArea();
9 }
10 // Method
11 calcArea() {
12 return this.height * this.width;
13 }
14}
15
16const square = new Rectangle(10, 10);
17
18console.log(square.area); // 100
1//Node js class: Here a quick code example
2
3// Basic class
4class Rectangle {
5
6 // Constructor
7 constructor(height, width) {
8 // Member variables
9 this.height = height;
10 this.width = width;
11
12 // Access static member variable
13 Rectangle.count++;
14 }
15
16 // Getter
17 get area() {
18 return this.calcArea();
19 }
20
21 // Method
22 calcArea() {
23 return this.height * this.width;
24 }
25
26 // Static method
27 static calcArea(width, height) {
28 return width * height;
29 }
30}
31
32// Static member variable
33Rectangle.count = 0;
34
35
36// Class instantiation
37const square = new Rectangle(10, 10);
38
39// Access member variable
40console.log(square.height, square.width); // 10 10
41
42// Call getter
43console.log(square.area); // 100
44
45// Call method
46console.log(square.calcArea()); // 100
47
48
49// Access static member variable
50console.log(Rectangle.count); // 1
51
52// Call static method
53console.log(Rectangle.calcArea(15, 15)); // 225
1class NameOfClass {
2//class declaration first letter should be capital it's a convention
3 obj="text";
4 obj2="some other text";
5}
6//always call class with "new" key word
7console.log(new NameOfClass);