Browser global object is window
and whenever you define global variables with var
or functions with function
, you are adding them in window
.
Thus you can get your "class" definition there:
var args = [];
var className = 'MyClass';
var obj = new window[className](args);
But this won't work for ES6 class declarations
Classes declared using ES6 keyword class
are per-standard treated differently.
A class declared with class MyClass { }
defines a global class that does not become a property of window
global object. In other words the following applies
class MyClass {};
typeof window.MyClass === 'undefined';
So, how to do the same with ES6 classes? Object access notation is required because is what is needed to parse the string name, but parent object to search in is no longer available.
One way is to create your own context object, declare there your class and search for it there. In code:
// this variable actually goes in `window`
var classes = {};
// declare class inside
classes.MyClass = class {
// the class code
};
var args = [];
var className = 'MyClass';
var obj = new classes[className](args); // dynamic for "new classes.MyClass(args)"