-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.js
More file actions
82 lines (61 loc) · 1.82 KB
/
class.js
File metadata and controls
82 lines (61 loc) · 1.82 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
ES6 feature: class
Note: Run this in browser not on node environment.
*/
class Person {
// These are not private fields but its a standard among developers community to indicate
// that anything that is prefixed with _ is internal to class don't modify or use directly.
// Use getters and setters instead.
_firstName = '';
_lastName = '';
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
// Similar to methods of class.
fullname() {
// return `${this._firstName} ${this._lastName}`; using private fields allowed
// using getters
return `${this.fname} ${this.lname}`;
}
// Getter
get fname() {
return this._firstName;
}
get lname() {
return this._lastName;
}
// Setter
set fname(name) {
if(name === '' || name === undefined) {
console.error('First name cannot be empty');
} else {
this._firstName = name;
}
}
whoiam() {
return `I'm ${this._firstName} ${this._lastName}!`;
}
}
let tty = new Person('Tai Tzu', 'Ying');
console.log(tty);
console.log(tty.fullname());
// Although its private we can access it.
console.log('Not private _firstName: ', tty._firstName);
// Accessing using getters
tty.fname;
// setting using setters
tty.fname = '';
// Inheritance using ES6 keywords
class Student extends Person {
constructor(firstName, lastName, course) {
// When extending from a base class super should be the first thing you call.
super(firstName, lastName);
this.course = course;
}
whoiam() {
return `${super.whoiam()} Am doing a course on ${this.course}!`
}
}
let lin = new Student('Lin', 'Dan', 'Badminton');
lin.whoiam();