1class ClassMates{
2 constructor(name,age){
3 this.name=name;
4 this.age=age;
5 }
6 displayInfo(){
7 return this.name + "is " + this.age + " years old!";
8 }
9}
10
11let classmate = new ClassMates("Mike Will",15);
12classmate.displayInfo(); // result: Mike Will is 15 years old!
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//JavaScript 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
1// unnamed
2let Rectangle = class {
3 constructor(height, width) {
4 this.height = height;
5 this.width = width;
6 }
7};
8console.log(Rectangle.name);
9// output: "Rectangle"
10
11// named
12let Rectangle = class Rectangle5 {
13 constructor(height, width) {
14 this.height = height;
15 this.width = width;
16 }
17};
18console.log(Rectangle.name);
19// output: "Rectangle2"
20
1class Rectangle {
2 constructor(hauteur, largeur) {
3 this.hauteur = hauteur;
4 this.largeur = largeur;
5 }
6}