-
Notifications
You must be signed in to change notification settings - Fork 1
/
classes.js
77 lines (62 loc) · 1.71 KB
/
classes.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
70
71
72
73
74
75
76
77
/** Classes **/
// Javascript is a functional programming language.
// However, the concept of Classes in ES6 is just syntax sugar on top of prototypal inheritance.
// The goal is to make the language more obvious to programmers coming from other paradigms (e.g. OO).
// ES5
function Counter () {
this.count = 0
}
Counter.prototype.increment = function (value) {
this.count++
}
Counter.prototype.decrement = function () {
this.count--
}
// Static method.
// A static method belongs to the class rather than the object of a class.
// We can invoke a static method with no need to create an instance.
Counter.isNil = function (counter) {
return counter.count === 0
}
let counter = new Counter()
counter.increment() // 1
counter.increment() // 2
counter.decrement() // 1
Counter.isNil(counter) // false
// ES6
class Counter {
constructor () {
this.count = 0
}
increment () {
this.count++
}
decrement () {
this.count--
}
static isNil (counter) {
return counter.count === 0
}
}
let counter = new Counter()
counter.increment() // 1
counter.increment() // 2
counter.decrement() // 1
Counter.isNil(counter) // false
// We now can use the keyword "extends" to easily "inherit" from other "classes".
// Not forgetting that this is only syntax sugar to ES5 prototype terminology.
class Temperature extends Counter {
constructor () {
// The super keyword identifies our base class "Counter".
super()
}
decrement () {
if(this.count > 0) {
super.decrement()
}
}
}
let termo = new Temperature()
termo.decrement() // 0 // no decrement because "count" was already 0
termo.increment() // 1
termo.decrement() // 0