So the answer to my question requires a little background knowledge. So I had 4 different base classes, for this case, let's just call them, class A, B, C, D. These classes were tested and proven to work. I then took these classes and turned them into JSON objected like such.
Class A
{
"props": {
"name": "Default Name",
"type": "A"
},
"functions": [
{
"name": "hello",
"params": [],
"body": ""
}
]
}
After completing this piece, I imported it into an object literal using the JSON.parse method. This allowed me to parse out the functions into form fields with dropdown menus for different logical statements one could make. I limited it to if/else conditionals, equality statements and return statements as those are the big three that most of the users would need access to, but I added an advance mode in case I needed to write something more custom.
After editing the properties of the functions, you would get something like this.
Class A Edited
{
"props": {
"name": "Default Name",
"type": "A_Edited"
},
"functions": [
{
"name": "hello",
"params": ["name"],
"body": "return `Hello, ${this.props.name}, my name is ${name}!`;"
}
]
}
After creating this new "class" from a pre-existing "class", you could create a new instance of the class by using the javascript spread operator and wrapping that in curly braces.
But how do you go from having text-based functions to an actual function that is bound to that new class? Here is the simple, but effective solution to that.
Class Factory
function ClassFactory(class){
class.functions.forEach((funct)=>{
var temporaryFunction = new Function(funct.params, funct.body);
class[funct.name] = temporaryFunction.bind(class);
})
return class;
}
JavaScript has a Function object, which has two parameters. The functions parameters and the body of that function. What this script is doing, is taking that newly created function, and binding it to a new property within the class, named after the original function. After the functions are bound to that class, it is then returned and voila! You have a class that has live functions that can be used.
So an example of that in effect is written below
var AEdited = ClassFactory(JSON.parse("/path/AEdited.json"));
var AEditedInstance = {...AEdited};
AEditedInstance.name = "Frank"
console.log(AEditedInstance.hello("Sam"));
/*
This would log "Hello Frank, I'm Sam"
*/
Let me know if you can think of anything that can improve this, but I can't think of a better way to dynamically create custom classes and then having them pushed to a static format for later use.