ES6 Object-Oriented Programming
# ES6 Object-Oriented Programming
// OOP encapsulation
class Student{ // Define a class (follows the convention of capitalizing the first letter)
constructor(props){ // Constructor (properties are defined inside the constructor)
this.name = props.name || 'Anonymous'; // Default 'Anonymous'
this.grade = props.grade || 1;
}
hello(){ // Define methods on the constructor's prototype
console.log(`Hello, ${this.name}, you are in grade ${this.grade}`);
}
}
// Usage
function createStudent(props) { // A wrapper for new constructor, with two benefits: 1) no need to use new, 2) flexible parameters
return new Student(props || {}) // Create an instance via new constructor and pass in parameters/properties
}
let niming = createStudent();
niming.hello();
let xiaoming = createStudent({
name:'Xiaoming',
grade:2
});
xiaoming.hello();
// Inheritance
class PrimaryStudent extends Student { // class ChildClass extends ParentClass
constructor(props) {
super(props); // Use super to call the parent's constructor to inherit properties
this.age = props.age || 8; // Add a new child class property
}
getAge() { // Add a method to the child class
console.log(`${this.name}, you are ${this.age} years old`);
}
}
// Using the inherited class
function createPrimaryStudent(props) { // A wrapper for new constructor, with two benefits: 1) no need to use new, 2) flexible parameters
return new PrimaryStudent(props || {}) // Create an instance via new constructor and pass in parameters/properties
}
let xiaohong = createPrimaryStudent({
name:'Xiaohong',
grade:3,
age:10
});
xiaohong.hello();
xiaohong.getAge();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Edit (opens new window)
Last Updated: 2026/03/21, 12:14:36