Skip to content

Instantly share code, notes, and snippets.

@AugustoPedraza
Created March 5, 2013 16:09
Show Gist options
  • Save AugustoPedraza/5091411 to your computer and use it in GitHub Desktop.
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".
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