0

I have a class and a function, as follows:

class A {} 
function B {}

I need to dynamically instantiate them, in a way similar to Java's class.forName().

I am able to instantiate the function as follows:

new window["B"]

However

window["A"] === undefined

Why the difference? Aren't classes just syntactic sugar for functions?

Irina Rapoport
  • 1,404
  • 1
  • 20
  • 37
  • 2
    "*Aren't classes just syntactic sugar for functions?*" mostly they are. But what you get here is the new scoping rules from ES6. Any `let`, `const`, and `class` declarations are *not* automatically added to the global object. Hence why you cannot get `A` from there. It'd be similar to having `const C = function() {}`. Although, not *exactly* the same - class constructors cannot be called without `new`. At any rate, if you need [“variable” variables](https://stackoverflow.com/q/5187530) just use an object or a map and put your classes there. You can then fetch them by string. – VLAZ Oct 30 '20 at 23:02
  • Also related: [Bind classes to Global Scope in ES6](https://stackoverflow.com/q/38796519) – VLAZ Oct 30 '20 at 23:06
  • So even when A is in my scope (A is defined), I can no longer evaluate "A"? – Irina Rapoport Oct 30 '20 at 23:14
  • That's correct. You could always do `window.A = A;` – Barmar Oct 30 '20 at 23:19
  • 1
    Not via a string. `A` exists in the current scope. This also happens to be the global scope. However, it's not added to the global object which is `window` for browsers. It's part of the design of ES6 to reduce the global pollution and name clashes. You can also just do `window.A = class A {}` but I'd really advise against it. If you need an object as a registry, then just use an object as a registry. – VLAZ Oct 30 '20 at 23:20
  • 1
    But it's better to use your own object for this rather than polluting the `window` object. – Barmar Oct 30 '20 at 23:20
  • @IrinaRapoport well you can always `eval('A')` if that's what you really want. But if you want to lookup some classes by strings, use a `Map`. – Bergi Oct 31 '20 at 04:58

0 Answers0