-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinheritanceTest.js
99 lines (78 loc) · 2.37 KB
/
inheritanceTest.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// requires inheritance.js
// requires /util/test.js
( () => {
const ok = [];
class Person { // refactoring Martin Fowler: replace inheritance with delegation
constructor(name) {
this.name = name;
this.worklog = [];
}
mustDo() { // design pattern: template method
return ""
}
work() {
this.worklog.push(this.mustDo())
}
}
const p = new Person("unknown");
ok.push(p.worklog.length === 0); // initially empty
p.work();
ok.push(p.worklog[0] === ""); // superclass impl
class Student extends Person {
mustDo() {
return "fill quiz"
}
}
const s = new Student();
ok.push(s.worklog.length === 0); // initially empty
s.work();
ok.push(s.worklog[0] === "fill quiz"); // subclass impl
ok.push(s.name === undefined); // super ctor not enforced
ok.push(s instanceof Student);
ok.push(s.__proto__ === Student.prototype);
ok.push(Object.getPrototypeOf(s) === Student.prototype);
ok.push(s instanceof Person);
ok.push(s instanceof Object);
ok.push(Student instanceof Function);
report("inheritance-ES6", ok);
})();
( () => {
const ok = [];
function Person(worker) {
const worklog = [];
return {
worklog: worklog,
work: () => worklog.push(worker.work())
}
}
const manager = Person( {work: () => ""} );
ok.push(manager.worklog.length === 0); // initially empty
manager.work();
ok.push(manager.worklog[0] === ""); // superclass impl
function Student(name) {
return {
name: name,
work: () => name + " filled quiz"
}
}
const p = Person(Student("top"));
ok.push(p.worklog.length === 0); // initially empty
p.work();
ok.push(p.worklog[0] === "top filled quiz"); // subclass impl
report("inheritance-delegate", ok);
})();
// todo: can you make the dk object an instanceof Person?
( () => {
const ok = [];
function Person(worker) {
const worklog = [];
const result = {
worklog: worklog,
work: () => worklog.push(worker.work())
};
return result
}
const dk = Person( {work: () => ""} );
ok.push(dk instanceof Person);
report("inheritance-setProto", ok);
})();