Variables declared with class
behave similarly to those declared with const
and let
- they do not get implicitly assigned to the window object (which is arguably a good thing). If you wanted to put Unit
on window
, you would have to do so explicitly:
class Unit {
constructor(){
console.log('constructing');
}
}
window.Unit = Unit;
var str = "Unit";
var a = new window[str]();
You might consider using your own object of classes to avoid global pollution:
const myClasses = {
Unit: class Unit {
constructor(){
console.log('constructing');
}
}
};
var str = "Unit";
var a = new myClasses[str]();
Object values cannot reference each other while in the process of declaring an object literal - to put a subclass on myClasses
that extends one of the existing classes, you'll have to do so outside of the myClasses
declaration:
const myClasses = {
Unit: class Unit {
constructor(){
console.log('constructing');
}
}
};
myClasses.Child = class Child extends myClasses.Unit {
constructor() {
super();
console.log('Child running');
}
}
var str = "Child";
var a = new myClasses[str]();