Skip to content

Instantly share code, notes, and snippets.

@tjstebbing
Created May 15, 2012 06:30
Show Gist options
  • Save tjstebbing/2699583 to your computer and use it in GitHub Desktop.
Save tjstebbing/2699583 to your computer and use it in GitHub Desktop.
Butterfly state machine ( http://harkablog.com/dynamic-state-machines.html ) in javascript
#!/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();
@schinckel
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment