0

So in the below code, i should be able to say let obj = Factory.create("class1",{})

const class1 = require("./class1")
const class2 = require("./class2")

class Factory{
    static create(className,params){
       return new className(params)
    }
}
module.exports=Factory
  • Maybe this post will help you out: https://stackoverflow.com/questions/1366127/instantiate-a-javascript-object-using-a-string-to-define-the-class-name – KfirM Aug 21 '18 at 10:25

3 Answers3

0

Try this:

let classes = {
    class1: require("./class1"),
    class2: require("./class2")
}
class Factory{
    static create(className,params){
       return new classes[className](params)
    }
}
module.exports=Factory
morteza ataiy
  • 541
  • 4
  • 12
0

If you are prepared to follow a certain naming convention, e.g. that class1 resides in class1.js, class2 resides in class2.js you can try the following:

index.js

let classes = {};

class Factory {
    static create(className, params) {
       if (!classes[className]) {
           classes[className] = require(`./${className}.js`);
       }
       console.log(`Creating ${className}...`);
       return new classes[className](params)
    }
}

let c1 = Factory.create('class1', {})
console.log(c1.sayHello());

let c2 = Factory.create('class2', {})
console.log(c2.sayHello()); 

class1.js

class class1 {
    sayHello() {
        return 'Hello from class1';
    }
}

module.exports = class1;

class2.js

class class2 {
    sayHello() {
        return 'Hello from class2';
    }
}

module.exports = class2;
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0

You don't. Classes are defined and referenced by a pointer just like everything else. You MUST have a way to refer to that pointer, whether by reference directly, or by reference in a map using a string. It's as simple as that in JS. Either you have access, or you don't. For string key based reference access you must have something to reference with said key. This is true in most other languages as well. There are a couple of answers here about it, but otherwise unless it's found on an object, a key will do you nothing.

var test = { 'a': 1 };

'test'; // "test"
'test'.a; // undefined

This is exactly how JS would interpret it. To reference test by string, you'd need to have something with the key test, otherwise JS has no way to interpret it.

This isn't a bad thing however since it would prevent someone sending you a string 'adminClass' and getting an instance of said class returned to them, exposing all sorts of dangerous things.

So for this paradigm, you're going to need a map of classes to go against. An Object should work just fine.

Robert Mennell
  • 1,954
  • 11
  • 24