lundi 23 septembre 2019

How to get ES6 class constructor from class name?

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





Aucun commentaire:

Enregistrer un commentaire