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!

12
  • param is a variable, you probably are looking for something like this: stackoverflow.com/questions/34655616/… Commented Mar 23, 2018 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]() Commented Mar 23, 2018 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. Commented Mar 23, 2018 at 14:19
  • 3
    Just remove the single quotes. let myClass2 = test(settings); Commented Mar 23, 2018 at 14:20
  • 1
    @csmckelvey: That would defeat the whole purpose of having a dynamic lookup. Commented Mar 23, 2018 at 14:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.