2
class Unit {
  constructor(){
  }
}    

var str = "Unit";
var a = new window[str](); // error
var b = new window["Unit"](); // error

var u = new Unit(); // works
    (u instanceof Unit) // true

I only recently made the switch to ES 6 syntax in regards to declaring classes. Im pretty sure that formerly i could instantiate a class like this, however ever since i have used "class" syntax, the instantiation of an object by windowclassName is not working anymore.

What exactly am i missing here ?

user431806
  • 396
  • 5
  • 17

1 Answers1

6

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]();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • One follow up if i may. When i want to declare Subunit extends Unit with the class-holding object, it does not work. Is there some special treatment necesarry here, like assigning and declaring the Subunit only after all baseclasses are in fact loaded ? – user431806 Apr 11 '19 at 10:26
  • See edit - you have to declare the child class after the `myClasses` object has finished being made. – CertainPerformance Apr 11 '19 at 10:29