Skip to content

Instantly share code, notes, and snippets.

@paulobsf
Created June 11, 2012 17:18
Show Gist options
  • Save paulobsf/2911406 to your computer and use it in GitHub Desktop.
Save paulobsf/2911406 to your computer and use it in GitHub Desktop.
JavaScript Prototypal Inheritance + Calling Parent Constructors
// https://speakerdeck.com/u/anguscroll/p/how-we-learned-to-stop-worrying-and-love-javascript
var Animal = function(gender, says) {
this.gender = gender;
this.says = says;
};
Animal.prototype.speak = function() {
console.log(this.says);
};
var WalkingAnimal = function(gender, says) {
Animal.call(this, gender, says);
};
WalkingAnimal.prototype = new Animal();
WalkingAnimal.prototype.walk = function() {
console.log('walking');
};
WalkingAnimal.prototype.turn = function(direction) {
console.log('turning', direction);
};
WalkingAnimal.prototype.stop = function() {
console.log('stopped walking');
};
var Elephant = function(gender) {
WalkingAnimal.call(this, gender, "whoooop");
}
Elephant.prototype = new WalkingAnimal();
Elephant.prototype.doCleverThingsWithTrunk = function() {
console.log("doing clever things with trunk");
}
var karela = new Elephant("male");
karela.walk();
karela.turn("right");
karela.stop();
karela.speak();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment