Classes (ES6) in JavaScript

class Foo { constructor() {} }. syntactic sugar over prototypes.

IntermediateObject ProgramsExample 2 of 2
classes-es6.js
1// Class declaration
2class Person {
3 constructor(name, age) {
4 this.name = name;
5 this.age = age;
6 }
7
8 greet() {
9 return `Hello, I'm ${this.name}`;
10 }
11
12 getAge() {
13 return this.age;
14 }
15}
16
17let person1 = new Person("Alice", 25);
18console.log(person1.greet());
19console.log("Age:", person1.getAge());
20
21// Class with inheritance
22class Student extends Person {
23 constructor(name, age, grade) {
24 super(name, age); // Call parent constructor
25 this.grade = grade;
26 }
27
28 study() {
29 return `${this.name} is studying`;
30 }
31
32 // Override parent method
33 greet() {
34 return `Hi, I'm ${this.name}, a student`;
35 }
36}
37
38let student1 = new Student("Bob", 20, "A");
39console.log("\nStudent:");
40console.log(student1.greet());
41console.log(student1.study());
42console.log("Grade:", student1.grade);
43
44// Static methods
45class MathUtils {
46 static add(a, b) {
47 return a + b;
48 }
49
50 static multiply(a, b) {
51 return a * b;
52 }
53}
54
55console.log("\nStatic methods:");
56console.log("Add:", MathUtils.add(5, 3));
57console.log("Multiply:", MathUtils.multiply(5, 3));
58
59// Getters and Setters
60class Circle {
61 constructor(radius) {
62 this._radius = radius;
63 }
64
65 get radius() {
66 return this._radius;
67 }
68
69 set radius(value) {
70 if (value > 0) {
71 this._radius = value;
72 } else {
73 throw new Error("Radius must be positive");
74 }
75 }
76
77 get area() {
78 return Math.PI * this._radius ** 2;
79 }
80}
81
82let circle = new Circle(5);
83console.log("\nCircle:");
84console.log("Radius:", circle.radius);
85console.log("Area:", circle.area.toFixed(2));
86circle.radius = 10;
87console.log("New radius:", circle.radius);
88console.log("New area:", circle.area.toFixed(2));

Output

Hello, I'm Alice
Age: 25

Student:
Hi, I'm Bob, a student
Bob is studying
Grade: A

Static methods:
Add: 8
Multiply: 15

Circle:
Radius: 5
Area: 78.54
New radius: 10
New area: 314.16

What's going on

constructor runs on new Foo(). Forget new and this is undefined in strict mode.

extends plus super() — skip super and the derived constructor throws.