Created
March 5, 2013 16:09
-
-
Save AugustoPedraza/5091411 to your computer and use it in GitHub Desktop.
Using inheritance with functional programming. This example was taken from the book "Javascript: The Good Parts".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mammal = function(spec){ | |
var that = {}; | |
that.getName = function( ){ | |
return spec.name; | |
}; | |
that.says = function( ){ | |
return spec.saying || ''; | |
}; | |
return that; | |
}; | |
var myMammal = mammal({ name: 'Herb' }); | |
console.log(myMammal.getName( )); | |
console.log(myMammal.says( )); | |
/*====================================*/ | |
var cat = function(spec){ | |
spec.saying = spec.saying || 'meow'; | |
var that = mammal(spec); | |
that.purr = function(n){ | |
var i, s = ''; | |
for(i=0; i<n; i+=1){ | |
if(s) s += '-'; | |
s += 'r' | |
} | |
return s; | |
}; | |
that.getName = function( ){ | |
return that.says( ) + ' ' + spec.name + ' ' + that.says( ); | |
} | |
return that; | |
}; | |
var myCat = cat({ name: 'Henrietta' }); | |
console.log(myCat.getName( )); | |
console.log(myCat.says( )); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment