Created
April 21, 2014 23:28
-
-
Save JoshuaKGoldberg/11160054 to your computer and use it in GitHub Desktop.
Dynamic Function Factory 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
/** | |
* Given a sketch of how a set of classes should look and inherit, this | |
* returns a set of functions to be used as constructors for those | |
* classes. | |
* | |
* @param {Object} inheritance A JSON representation of the classes' | |
* inheritance, with each parent object | |
* containing the objects of its children, | |
* all keyed by name. | |
* @param {Object} properties An object containing the properties for | |
* each class type, keyed by name. | |
* @return {Object} An object containing each constructor function, | |
* keyed by name | |
* | |
* @author Josh Goldberg josh@joshuakgoldberg.com | |
*/ | |
function createFunctions(inheritance, properties) { | |
var functions = {}; | |
function processFunctions(tree, Parent) { | |
var name, ref, func; | |
// For each name in the current inheritance object ("Bird", "Cat", "Dog"...): | |
for(name in tree) { | |
if(tree.hasOwnProperty(name)) { | |
// Create a new function under this name (functions["Bird"]) | |
func = functions[name] = function() {}; | |
// functions["Bird"].prototype = new Animal(); | |
func.prototype = new Parent(); | |
// Add each property from properties to the prototype | |
for(ref in properties[name]) { | |
if(properties[name].hasOwnProperty(ref)) { | |
func.prototype[ref] = properties[name][ref]; | |
} | |
} | |
// Recurse on each child, with the new function as the Parent | |
processFunctions(tree[name], func); | |
} | |
} | |
} | |
// Start the recursion on the root objects, with Object as the parent | |
processFunctions(inheritance, Object); | |
return functions; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment