@@ -5,5 +5,61 @@ $(document).ready(function(){
55
66 module ( "About Prototypal Inheritance (topics/about_prototypal_inheritance.js)" ) ;
77
8+ // this 'class' pattern defines a class by its constructor
9+ var Mammal = function ( name ) {
10+ this . name = name ;
11+ }
12+ // things that don't need to be set in the constructor should beadded to the constructor's prototype property.
13+ Mammal . prototype = {
14+ sayHi : function ( ) {
15+ return "Hello, my name is " + this . name ;
16+ }
17+ }
18+
19+ test ( "defining a 'class'" , function ( ) {
20+ var eric = new Mammal ( "Eric" ) ;
21+ equals ( eric . sayHi ( ) , __ , 'what will Eric say?' ) ;
22+ } ) ;
23+
24+ // add another function to the Mammal 'type' that uses the sayHi function
25+ Mammal . prototype . favouriteSaying = function ( ) {
26+ return this . name + "'s favourite saying is " + this . sayHi ( ) ;
27+ }
28+
29+ test ( "more functions" , function ( ) {
30+ var bobby = new Mammal ( "Bobby" ) ;
31+ equals ( bobby . favouriteSaying ( ) , __ , "what is Bobby's favourite saying?" ) ;
32+ } ) ;
33+
34+ test ( "calling functions added to a prototype after an object was created" , function ( ) {
35+ var paul = new Mammal ( "Paul" ) ;
36+ Mammal . prototype . numberOfLettersInName = function ( ) {
37+ return this . name . length ;
38+ } ;
39+ // for the following statement asks the paul object to call a function that was added to the Mammal prototype after paul was constructed.
40+ equals ( paul . numberOfLettersInName ( ) , __ , "how long is Paul's name?" ) ;
41+ } ) ;
42+
43+ // helper function for inheritance.
44+ // From https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_Revisited
45+ function extend ( child , supertype ) {
46+ child . prototype . __proto__ = supertype . prototype ;
47+ }
48+
49+ // "Subclass" Mammal
50+ function Bat ( name , wingspan ) {
51+ Mammal . call ( this , name ) ;
52+ this . wingspan = wingspan ;
53+ }
54+
55+ // configure inheritance
56+ extend ( Bat , Mammal ) ;
57+
58+ test ( "Inheritance" , function ( ) {
59+ var lenny = new Bat ( "Lenny" , "1.5m" ) ;
60+ equals ( lenny . sayHi ( ) , __ , "what does Lenny say?" ) ;
61+ equals ( lenny . wingspan , __ , "what is Lenny's wingspan?" ) ;
62+ } ) ;
63+
864
965} ) ;
0 commit comments