Created
May 5, 2016 22:25
-
-
Save santiago-puch-giner/15a262a179b7ec86cba67438b3ae2dcb to your computer and use it in GitHub Desktop.
Prototype inheritance in Javascript
This file contains hidden or 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
// 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