Created
May 15, 2012 06:30
-
-
Save tjstebbing/2699583 to your computer and use it in GitHub Desktop.
Butterfly state machine ( http://harkablog.com/dynamic-state-machines.html ) in javascript
This file contains 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
#!/usr/bin/node | |
/* butterfly state machine */ | |
var Egg = function(species) { | |
this.species = species; | |
console.log("An egg"); | |
this.hatch = function() { | |
this.__proto__ = new Catterpiller(); | |
console.log(this.species, "hatching, check out my", this.legs, "legs!"); | |
} | |
}; | |
var Catterpiller = function() { | |
this.legs = 16; | |
this.crawl = function() { | |
console.log("crawling"); | |
}; | |
this.eat = function() { | |
console.log("eating"); | |
}; | |
this.pupate = function() { | |
this.__proto__ = new Pupa(); | |
console.log(this.species, "Pupating!"); | |
} | |
}; | |
var Pupa = function() { | |
this.emerge = function() { | |
this.__proto__ = new Butterfly(); | |
} | |
}; | |
var Butterfly = function() { | |
this.fly = function() { | |
console.log("flying"); | |
}; | |
this.eat = function() { | |
console.log("eating"); | |
}; | |
this.reproduce = function() { | |
return new Egg(this.species); | |
} | |
}; | |
critter = new Egg('Morpho menelaus'); | |
critter.hatch(); | |
critter.crawl(); | |
critter.eat(); | |
critter.pupate(); | |
critter.emerge(); | |
critter.fly(); | |
offspring = critter.reproduce(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's all well and good, but IIRC
__proto__
is an implementation detail. This may work in node, and most browsers, but in I believe it will fail in some IE browsers.According to an answer on http://www.quora.com/JavaScript/What-is-the-difference-between-__proto__-and-prototype, you should not use it.