1

I have a question which shouldn't be to difficult, but I've been spending days and can't seem to find the answer. All the solutions I found didn't help me, they all threw errors.

I made a Class in Javascript and want to create a new instance dynamically, so that I can instantiate multiple classes depending on the parameter in a function. It doesn't seem te work, and I wonder why.

settings.js and main.js are loaded via <script> tag in the HTML file, with settings.js being loaded first.

main.js

let myClass = new settings(); // Works
let myClass2 = test('settings'); // Error: Uncaught TypeError: param is not a constructor

function test(param){
  return new param();
}

settings.js

class settings{

  constructor(){
    console.log("works");
  }
}

Thanks for any help!

  • param is a variable, you probably are looking for something like this: https://stackoverflow.com/questions/34655616/create-an-instance-of-a-class-in-es6-with-a-dynamic-name – briosheje Mar 23 '18 at 14:19
  • 1
    You cant just instantiate a string, you could probably use the string to look up the class though, e.g. `new window[param]()` – Marie Mar 23 '18 at 14:19
  • 2
    Well, the error is very succinct. You're passing in 'settings' as an argument and expecting the function to return an instance of it. But it's not a constructor - it's a string. – Andy Mar 23 '18 at 14:19
  • 3
    Just remove the single quotes. `let myClass2 = test(settings);` – takendarkk Mar 23 '18 at 14:20
  • 1
    @csmckelvey: That would defeat the whole purpose of having a dynamic lookup. – H.B. Mar 23 '18 at 14:21
  • https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string – Matt Burland Mar 23 '18 at 14:21
  • @H.B. OP doesn't want dynamic lookup. – melpomene Mar 23 '18 at 14:21
  • @H.B. what do you mean by "dynamic lookup" you can't pass a string and expect it to magically return the class that is named the same. – Ryan Schaefer Mar 23 '18 at 14:22
  • csmckelvey, removing the quotes worked. I'll look into the other answers aswell, thanks all! – Peter Iedema Mar 23 '18 at 14:22
  • Your problem can be reduced to: `console.log(42); // works` and `var x = 42; console.log('x'); // doesn't work` – melpomene Mar 23 '18 at 14:23
  • @RyanSchaefer: Yes you can, if passed as a key to an object for example as noted by Marie. – H.B. Mar 23 '18 at 14:23
  • I would have answered that you should implement a Factory style design pattern in JS with sample code but a question marked as "duplicate" is locked. Why am I suggesting Googling "Javascript Factory design pattern example"? Well you're trying to define a function that will return a class object depending on the variable value passed to it. If you intend to define more than one class value (e.g. "settings", "config", "action") then you'll be basically following a Factory pattern. A quick Google will reveal a bunch of good examples. – dubmojo Mar 23 '18 at 14:31

0 Answers0