Skip to content

Instantly share code, notes, and snippets.

@santiago-puch-giner
Created May 5, 2016 22:25
Show Gist options
  • Save santiago-puch-giner/15a262a179b7ec86cba67438b3ae2dcb to your computer and use it in GitHub Desktop.
Save santiago-puch-giner/15a262a179b7ec86cba67438b3ae2dcb to your computer and use it in GitHub Desktop.
Prototype inheritance in Javascript
// Snippet showing inheritance through prototypes
var Animal = function(type){
this.type = type;
};
Animal.prototype.eat = function(){
console.log("They eat food to survive.");
};
var Mammal = function(){};
// Mammal inherits from Animals
Mammal.prototype = new Animal();
Mammal.prototype.giveBirth = function(){
console.log("They give birth to young ones.");
};
var elephant = new Mammal(); //Creating instance of type Mammal
elephant.eat(); //elephant can use the inherited method from Animal.
elephant.giveBirth();
console.log(elephant instanceof Mammal); // true
console.log(elephant instanceof Animal); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment