Skip to content

Instantly share code, notes, and snippets.

@simonewebdesign
Created May 16, 2013 10:47
Show Gist options
  • Save simonewebdesign/5590870 to your computer and use it in GitHub Desktop.
Save simonewebdesign/5590870 to your computer and use it in GitHub Desktop.
Simple JavaScript inheritance
function Animal() {
/* properties */
this.isWild = true;
this.name = '';
this.sound = '';
this.height = 0; // cm
this.weight = 0; // kg
this.speed = 0; // km/h
this.age = 0; // years old
/* methods */
this.cry = function() {
console.log(this.name + ' says: ' + this.sound + '!');
}
this.run = function() {
console.log(this.name + ' is running at ' + this.speed + 'km/h!');
}
this.eat = function() {
console.log(this.name + ' is eating!');
}
}
function Cat(){
this.inheritFrom = Animal;
this.inheritFrom();
}
Cat.prototype = new Animal;
function Dog(){
this.inheritFrom = Animal;
this.inheritFrom();
}
Dog.prototype = new Animal;
//testing...
var kitteh = new Cat();
kitteh.name = "Kitty";
console.log(kitteh instanceof Cat); // should be true
console.log(kitteh instanceof Animal); // should be true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment