1
+ function Muppet ( age , hobby ) {
2
+ this . age = age ;
3
+ this . hobby = hobby ;
4
+
5
+ this . answerNanny = function ( ) {
6
+ return "Everything's cool!" ;
7
+ }
8
+ }
9
+
10
+ function SwedishChef ( age , hobby , mood ) {
11
+ Muppet . call ( this , age , hobby ) ;
12
+ this . mood = mood ;
13
+
14
+ this . cook = function ( ) {
15
+ return "Mmmm soup!" ;
16
+ }
17
+ }
18
+
19
+ SwedishChef . prototype = new Muppet ( ) ;
20
+
21
+ describe ( "About inheritance" , function ( ) {
22
+ beforeEach ( function ( ) {
23
+ this . muppet = new Muppet ( 2 , "coding" ) ;
24
+ this . swedishChef = new SwedishChef ( 2 , "cooking" , "chillin" ) ;
25
+ } ) ;
26
+
27
+ it ( "should be able to call a method on the derived object" , function ( ) {
28
+ expect ( this . swedishChef . cook ( ) ) . toEqual ( __ ) ;
29
+ } ) ;
30
+
31
+ it ( "should be able to call a method on the base object" , function ( ) {
32
+ expect ( this . swedishChef . answerNanny ( ) ) . toEqual ( __ ) ;
33
+ } ) ;
34
+
35
+ it ( "should set constructor parameters on the base object" , function ( ) {
36
+ expect ( this . swedishChef . age ) . toEqual ( __ ) ;
37
+ expect ( this . swedishChef . hobby ) . toEqual ( __ ) ;
38
+ } ) ;
39
+
40
+ it ( "should set constructor parameters on the derived object" , function ( ) {
41
+ expect ( this . swedishChef . mood ) . toEqual ( __ ) ;
42
+ } ) ;
43
+ } ) ;
44
+
45
+ // http://javascript.crockford.com/prototypal.html
46
+ Object . prototype . beget = function ( ) {
47
+ function F ( ) { }
48
+ F . prototype = this ;
49
+ return new F ( ) ;
50
+ }
51
+
52
+ function Gonzo ( age , hobby , trick ) {
53
+ Muppet . call ( this , age , hobby ) ;
54
+ this . trick = trick ;
55
+
56
+ this . doTrick = function ( ) {
57
+ return this . trick ;
58
+ }
59
+ }
60
+
61
+ //no longer need to call the Muppet (base type) constructor
62
+ Gonzo . prototype = Muppet . prototype . beget ( ) ;
63
+
64
+ describe ( "About Crockford's inheritance improvement" , function ( ) {
65
+ beforeEach ( function ( ) {
66
+ this . gonzo = new Gonzo ( 3 , "daredevil performer" , "eat a tire" ) ;
67
+ } ) ;
68
+
69
+ it ( "should be able to call a method on the derived object" , function ( ) {
70
+ expect ( this . gonzo . doTrick ( ) ) . toEqual ( __ ) ;
71
+ } ) ;
72
+
73
+ it ( "should be able to call a method on the base object" , function ( ) {
74
+ expect ( this . gonzo . answerNanny ( ) ) . toEqual ( __ ) ;
75
+ } ) ;
76
+
77
+ it ( "should set constructor parameters on the base object" , function ( ) {
78
+ expect ( this . gonzo . age ) . toEqual ( __ ) ;
79
+ expect ( this . gonzo . hobby ) . toEqual ( __ ) ;
80
+ } ) ;
81
+
82
+ it ( "should set constructor parameters on the derived object" , function ( ) {
83
+ expect ( this . gonzo . trick ) . toEqual ( __ ) ;
84
+ } ) ;
85
+ } ) ;
0 commit comments