4

I’m writing an application right now that calls for a user to be able to either select an object type from predefined list of objects or generate a new sibling object type through a front end system. So it would kinda look like this example below

`
    class predefinedClass extends someParentClass{
        ...
    }

    //Some user defined class
    class dynamicClass extends someParentClass{
        ...
    }

`

So does anyone have experience in generating a dynamic class? I’ve got a hunch that a functional approach might be easier than an OOP approach, but I figured it’s worth the shot.

  • 1
    You could always use text generation then eval.. But I suspect anything that can be done using class generation could be done using object prototypes easier. Looking forward to an answer, good question. – Ryan Leach Sep 25 '18 at 02:06
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Mix-ins might be a good hint towards a good answer. – Ryan Leach Sep 25 '18 at 02:09
  • 1
    https://stackoverflow.com/a/46132163/2813224 – zer00ne Sep 25 '18 at 05:53
  • So I actually went with text generation. Nothing that any of you guys said was wrong and I actually learned some things along the way, but with proper form controls, I could generate both a dynamic class in runtime and then create a static class for later use. – basicallysteve Oct 04 '18 at 19:35

1 Answers1

0

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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • If you want to remove your answer, use the flag link to get it removed permanently. Content on Stack Overflow is licensed under a Creative Commons License. You'll need a moderator to delete the answer and its history. – Heretic Monkey Jul 30 '19 at 20:31