Created
February 12, 2015 23:23
-
-
Save ptgamr/a92dafa727e6083f81da to your computer and use it in GitHub Desktop.
Father & Son Analogy
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
// https://alexsexton.com/blog/2013/04/understanding-javascript-inheritance/ | |
// Let's take a set of 4 genes for ease of | |
// example here. We'll put them in charge | |
// a few things. | |
function Human (name, genes_mom, genes_dad) { | |
this.name = name; | |
// Set the genes | |
this.genes = { | |
darkHair: this._selectGenes(genes_mom.darkHair, genes_dad.darkHair), | |
smart: this._selectGenes(genes_mom.smart, genes_dad.smart), | |
athletic: this._selectGenes(genes_mom.athletic, genes_dad.athletic), | |
tall: this._selectGenes(genes_mom.tall, genes_dad.tall) | |
}; | |
// Since genes affect you since birth we can set these as actual attributes | |
this.attributes = { | |
darkHair: !!(~this.genes.darkHair.indexOf('D')), | |
smart: !!(~this.genes.smart.indexOf('D')), | |
athletic: !!(~this.genes.athletic.indexOf('D')), | |
tall: !!(~this.genes.tall.indexOf('D')) | |
}; | |
} | |
// You don't have access to your own gene selection | |
// so we'll make this private (but in the javascript way) | |
Human.prototype._selectGenes = function (gene1, gene2) { | |
// Assume that a gene is a 2 length array of the following possibilities | |
// DD, Dr, rD, rr -- the latter being the only non "dominant" result | |
// Simple random gene selection | |
return [ gene1[Math.random() > 0.5 ? 1 : 0], gene2[Math.random() > 0.5 ? 1 : 0] ] | |
}; | |
Human.prototype.sayHi = function () { | |
console.log("Hello, I'm " + this.name); | |
}; | |
function makeBaby(name, mother, father) { | |
// Send in the genes of each parent | |
var baby = new Human(name, mother.genes, father.genes); | |
return baby; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment