0

Given the following code:

class MyClass {}

Is there a way to get the MyClass constructor from the string, MyClass? I'm looking for something analogous to .NET's Assembly.GetType.

Use case:

A user of a product authors their own classes via some sort of extensibility; and these classes should be able to be loaded from the global scope by the product when the product is given the name of a given class.

I understand that in most cases this would likely be a terrible design pattern lacking encapsulation, but nonetheless I am curious if this type of reflection is possible in any ECMAScript version. The way I work around this is to have each class "register" itself using a helper function (or class decorator!) from the main product.

P.S.

I notice that while function declarations alter the global scope, class definitions do not:

function hithere() {}
globalThis["hithere"] // hithere(){}
class hithere {}
globalThis["hithere"] // undefined
Peter Fernandes
  • 307
  • 1
  • 9
  • 1
    Not necessarily because in JS a class definition is just another variable storing some value. So you could as well write `const Foo = class Bar {}`. Guess what the "name" would be now. – Thomas Sep 23 '19 at 13:57
  • if you were to do `window.hithere= class hithere {}` you could access it with `globalThis` like in the first example – Krzysztof Krzeszewski Sep 23 '19 at 13:58
  • Not without parsing the code yourself to find `class` definitions or requiring the code to explicitly register or export the desired classes. Personally, I like modules so I'd suggest you change the format to a module format and require the code writer to export the classes in some agreed-upon export format. The module format would also put everything in a private scope and prevent name clashes. – jfriend00 Sep 23 '19 at 13:58

0 Answers0