-
Notifications
You must be signed in to change notification settings - Fork 0
/
class.js
69 lines (52 loc) · 1.71 KB
/
class.js
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
// ES6 Class
// 1. Class Definition
// Base class
class User {
// class constructor
constructor(firstname, lastname, age) {
// properties
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
}
// a method - getter
getFullName() { return `${this.firstname} ${this.lastname}`; }
// another method - setter
editName(newname) {
const myname = newname.split(' ');
this.firstname = myname[0];
this.lastname = myname[1];
}
}
// create a new object of type 'User'
const John = new User('John', 'Anderson', 21);
console.log(John);
// if nothing is passed for the constructor
const Sammy = new User();
console.log(Sammy); // -> all keys undefined
// calling class methods
console.log(John.getFullName()); // -> John Anderson
John.editName('Jhonny Anderson');
console.log(John.getFullName()); // -> Jhonny Anderson
// 2. Inheritance and Method Overriding
// Derived(Sub) Class
class Teacher extends User {
// class constructor
constructor(firstname, lastname, age, subject) {
// parent class constructor
super(firstname, lastname, age); // necessary!
// property
this.subject = subject;
}
// method overriding
getFullName() { return `Prof. ${this.firstname} ${this.lastname}`; }
} // ^^^^^--- added
// a new object of type 'Teacher'
const tim = new Teacher('Tim', 'Barton', 50, 'DSA');
// inherited property
console.log(`${tim.firstname}'s age: ${tim.age}`); // -> Tim's age: 50
// overriden method
console.log(tim.getFullName()); // -> Prof. Tim Barton
// inherited method
tim.editName('Tim Roughgarden');
console.log(tim.getFullName()); // -> Prof. Tim Roughgarden