Last active
December 15, 2015 02:48
-
-
Save BrianHicks/5189308 to your computer and use it in GitHub Desktop.
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
// mostly stolen from http://phrogz.net/JS/classes/OOPinJS2.html | |
// first we define a mammal... | |
function Mammal(name) { | |
this.name = name; | |
this.offspring = []; | |
} | |
Mammal.prototype.haveABaby = function() { | |
var newBaby = new Mammal("Baby " + this.name); | |
this.offspring.push(newBaby); | |
return newBaby; | |
} | |
Mammal.prototype.toString = function() { return '[Mammal "' + this.name + '"]'; } | |
// let's use our new class to describe some mammals! | |
var gerald = new Mammal("Gerald"); | |
console.log("Gerald is " + gerald); // Gerald is [Mammal "Gerald"] | |
// But obviously we need to be more specific than this. How about a cat? | |
function Cat(name) { | |
this.name = "Reverend Mc" + name; | |
} | |
Cat.prototype = new Mammal(); | |
Cat.prototype.constructor = Cat; // otherwise Cats would have the constructor of Mammal | |
Cat.prototype.toString = function() { return '[Cat "' + this.name + '"]'; } | |
// so now we have cats, too. | |
var phil = new Cat("Phil"); | |
console.log("Phil is " + phil); // Phil is [Cat "Reverend McPhil"] | |
// oh snap! Phil's actually a Phyllis! | |
var lilPhil = phil.haveABaby(); | |
console.log('lilPhil is ' + lilPhil); // lilPhil is [Cat "Baby Reverend McPhil"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment