BTW: window is the reference to the global Object in browser JavaScript. Which is also this
, and should work even in non-browser environments such as Node.js, Chrome extensions, transpiled code etc.
var obj = new this[classNameString]();
The limitation is that the class being called must be in the global context. If you want to apply the same to a scoped class you need to do:
var obj = (Function('return new ' + classNameString))()
However, there really is no reason to use a string. JavaScript functions are themselves objects, just like strings which are objects also.
Edit
Here is a better way to get the global scope that works in strict mode as well as non-browser JS environments:
var global;
try {
global = Function('return this')() || (42, eval)('this');
} catch(e) {
global = window;
}
// and then
var obj = new global[classNameString]
From: How to get the global object in JavaScript?