ES5 Object-Oriented Programming
# ES5 Object-Oriented Programming
// OOP encapsulation
function Student(props){ // Constructor (properties are defined inside the constructor. Follows the convention of capitalizing the first letter)
this.name = props.name || 'Anonymous'; // Default 'Anonymous'
this.grade = props.grade || 1;
}
Student.prototype.hello = function(){ // 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
}
var niming = createStudent();
niming.hello();
var xiaoming = createStudent({
name:'Xiaoming',
grade:2
});
xiaoming.hello();
// Inheritance
function inherits(Child, Parent) { // Inheritance wrapper method: inherits(ChildClass, ParentClass)
var F = function () {}; // Define an empty function F
F.prototype = Parent.prototype; // Point F's prototype to the parent's prototype
Child.prototype = new F(); // Point the child's prototype to new F()
Child.prototype.constructor = Child; // Fix the constructor on the child's prototype to point to the child class itself
}
function PrimaryStudent(props) { // Define the child class constructor
Student.call(this, props); // Fix the this reference
this.age = props.age || 8; // Add a new child class property
}
inherits(PrimaryStudent, Student); // Call the inheritance wrapper to implement inheritance
PrimaryStudent.prototype.getAge = function(){ // 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
}
var 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
55
56
57
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
55
56
57
Edit (opens new window)
Last Updated: 2026/03/21, 12:14:36