1

I'm wondering if this is a Chrome issue or it's by design (which would be inconsistent with all other objects in JavaScript).

Classes can't be instantiated dynamically like other objects. Consider this code:

class BaseClass {

}

And somewhere you want to dynamically create instance of this class:

var inst;
if (window[fnName].constructor) {
  try {
    inst = new window[fnName](value);
  } catch (e) {}
} else {
  inst = window[fnName](value);
}

Code from function above will fail (at leas in strict mode) because window object does not contain BaseClass. And this is not natural in JavaScript because defined objects / function are available in window object.

if I change the code to

return new BaseClass(value);

it is working as it should. So where classes definitions are kept? In global object? Not really. But they are available. Help me solve this.

Pawel Uchida-Psztyc
  • 3,735
  • 2
  • 20
  • 41
  • 1
    …or duplicate of [Create object from string in JavasScript ECMAScript 6](http://stackoverflow.com/a/31790015/1048572) – Bergi Feb 23 '16 at 16:11
  • I thought it was a duplicate but your question is a little different. – A1rPun Feb 23 '16 at 16:11
  • 1
    `let` and `const` and other lexical declarations are not available as properties of the global object as well. They are *only* variables in the global scope. – Bergi Feb 23 '16 at 16:12
  • 1
    @A1rPun your first comment was right. It is an answer for my question. Nod directly but I see now that classes are not global properties by design. So my code above will work only if I "export" class to window object like `window.BaseClass = BaseClass`. Not very developer friendly and I have no idea why language designers decided to make it works this way but I need to adjust I guess. – Pawel Uchida-Psztyc Feb 23 '16 at 16:19
  • 1
    @PawełPsztyć Yeah it differs from ES5, hope you will find your workaround ;) for future reference, [I linked this post originally](http://stackoverflow.com/q/30321636/1449624) – A1rPun Feb 23 '16 at 16:24
  • 3
    Populating the global scope with random constructors is also not developer-friendly :) That's what modules are for. – loganfsmyth Feb 23 '16 at 17:22
  • @loganfsmyth exactly - so if I'd like to declare a module I'd do that. But when I'm declaring something in a global scope I'm expecting the object to be in this scope - like any other object declared this way. – Pawel Uchida-Psztyc Feb 23 '16 at 19:57
  • Cool, just clarifying. – loganfsmyth Feb 23 '16 at 22:05

0 Answers0