forked from mrdavidlaing/javascript-koans
-
Notifications
You must be signed in to change notification settings - Fork 482
Expand file tree
/
Copy pathAboutInheritance.js
More file actions
89 lines (71 loc) · 2.49 KB
/
AboutInheritance.js
File metadata and controls
89 lines (71 loc) · 2.49 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
83
84
85
86
87
88
89
function Muppet(age, hobby) {
this.age = age;
this.hobby = hobby;
this.answerNanny = function(){
return "Everything's cool!";
}
}
function SwedishChef(age, hobby, mood) {
Muppet.call(this, age, hobby);
this.mood = mood;
this.cook = function() {
return "Mmmm soup!";
}
}
SwedishChef.prototype = new Muppet();
describe("About inheritance", function() {
beforeEach(function(){
this.muppet = new Muppet(2, "coding");
this.swedishChef = new SwedishChef(2, "cooking", "chillin");
});
it("should be able to call a method on the derived object", function() {
expect(this.swedishChef.cook()).toEqual(FILL_ME_IN);
});
it("should be able to call a method on the base object", function() {
expect(this.swedishChef.answerNanny()).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the base object", function() {
expect(this.swedishChef.age).toEqual(FILL_ME_IN);
expect(this.swedishChef.hobby).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the derived object", function() {
expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
});
});
// https://www.crockford.com/javascript/prototypal.html
Object.prototype.beget = function () {
function F() {}
F.prototype = this;
return new F();
}
function Gonzo(age, hobby, trick) {
Muppet.call(this, age, hobby);
this.trick = trick;
this.doTrick = function() {
return this.trick;
}
}
//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
// var g = new Gonzo(...);
// g instanceOf Muppet //true
describe("About Crockford's inheritance improvement", function() {
beforeEach(function(){
this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
});
it("should be able to call a method on the derived object", function() {
expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
});
it("should be able to call a method on the base object", function() {
expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the base object", function() {
expect(this.gonzo.age).toEqual(FILL_ME_IN);
expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the derived object", function() {
expect(this.gonzo.trick).toEqual(FILL_ME_IN);
});
});