Suppose the array contains the class names

var arr = ['class1','class2','class3' и т.д.]; 

I need to load these classes sequentially along with constructors, etc. Classes are defined earlier by code.

doing this now

 for(let key in arr){ let obj = new arr[key]; // здесь дальнейшая работа с объектом } 

but an error flies because arr contains the names of the classes, not the classes themselves.

how to be?

    2 answers 2

    If it is not Node.js :

     for(let key in arr){ var myClass = window[arr[key]]; let obj = new myClass; // здесь дальнейшая работа с объектом } 
    • and if node.js ??? then?? - Ivashka
    • @ Ivashka, Try global instead of window . - Max

    In such a non-usual way, you can get a class / function (the constructor function is called a class). Works for any global object.

     class class1 { // я class } function class2 () { // я function } const arr = ['class1', 'class2'] for(let str of arr) { let myClass = (new Function(`return ${str};`))() console.log(myClass) } 

    A normal function can be obtained through window, but the class does not exist, only if you write it manually:

     window.Foo = class Foo { ... } 

    In more detail about classes that are not properties of a window object in this answer , which cites ECMA2015 specification, section 8.1.1.4: Global environmental records :

    Record and a declarative Environment Record. It is a global object of the Realm. Record's GetThisBinding concrete method. (TJ) It is a global environment and it has been developed by the United States. in global code. ECMAScript for the global environment.

    That is, the innovations (let, const, and class declarations) are not available in the global object, this can be seen from this code:

     let a = 1 const b = 2 class c {} console.log(window.a, window.b, window.c)