0

Why globalThis does not include classes (like it includes functions)? Is there other 'this' that includes them?

What I want is to instantiate a class from a string, after checking it is defined, but it does not work the same I am doing for functions. For functions I check the function is defined in globalThis and if yes I call it. But for classes does not work.

My code:

class Foo {
  constructor() {}
  foobar(i) {return i+1;}
}

function bar(i) {
  return i+1;
}

function myFunction() {
  if (globalThis['bar'])
    console.log(globalThis['bar'](3)); // This works fine, it calls the function bar

  if (globalThis['Foo'])
    console.log((new globalThis['Foo']).foobar(3)); // never reaches here!!
  
}

I have checked how globalThis looks and it seems it does not include the class, but only the functions!! :

console.log(globalThis);

gives the following output:

{ myFunction: [Function: myFunction], bar: [Function: bar] }

I am using GAS, but I assume this is javascript generic.

elena
  • 53
  • 5
  • 2
    Top-level names declared with `function` and `var` are added to the global object for historical reasons. All the defining keywords added in ES6 do not add to the global object. These are `class`, `let`, and `const`. – Barmar Aug 05 '22 at 19:08
  • Ok, then how can I check if the class is defined and then instantiate it? – elena Aug 05 '22 at 19:39
  • 1
    You can use `globalThis.Foo = Foo;` after defining the class. – Barmar Aug 05 '22 at 19:40
  • 1
    `if (typeof Foo != "undefined") new Foo().foobar(3);` – Barmar Aug 05 '22 at 19:41
  • oh, ok, then in my case I guess it would be ```if (eval(`typeof `+`Foo`) != "undefined")``` because I create the class from the string – elena Aug 05 '22 at 19:52
  • 2
    Avoid `eval()`. Create a global object that holds your classes. `myClasses['Foo'] = Foo;`. Then you can do `if (myClasses['Foo']) new myClasses['Foo']().foo(6)` – Barmar Aug 05 '22 at 19:54
  • Sounds very good, thank you – elena Aug 05 '22 at 19:55

0 Answers0