2

In a regular script a function can be invoked by string name as window["myFunc"]().

Is there an equivalent in a JS script of type="module" at the "top level", apart from declaring an object and assigning a method to it?

Thank you.

Gary
  • 2,393
  • 12
  • 31

2 Answers2

2

No - one of the main benefits of modules is to allow code that avoids that sort of global pollution. The top level of a module works similarly to an IIFE - the module can see everything that's global, but nothing can see what's declared inside the module, except that, also:

  • Modules can import from other modules
  • Modules can export to other modules

While you technically can do something like

window.foo = 'foo';

inside a module, writing scripts that use that route defeats the purpose of using a module system at all. Explicit dependencies make code more maintainable.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Within a module's scope or its inner global namespace (I don't know a better term for it) to what are function delcarations assigned? – Gary Sep 16 '22 at 01:05
  • To the environment that is the top level of the module - just like how standard variable definitions `const foo = 'bar';` are assigned to their environment (which is usually the enclosing block - or top level, if there is no enclosing block). If you're not doing anything [*weird*](https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6) and understand the hoisting implications, you can consider `function fn() { ...` to be equivalent to `const fn = function() {` for most purposes - it's just like the declaration of another variable. – CertainPerformance Sep 16 '22 at 01:08
  • Thank you. I wasn't getting it, of course; but seem to understand now. – Gary Sep 16 '22 at 01:21
  • Not sure I quite agree with that this is a benefit. Clearly you can define variables in a module directly without defining them inside another scope, but for some reason you cant access this "module" scope like you can global scope through "window" parent object. I wish there was at least a "module" object that you could access within the module itself. The extreme flexibility of Javascript is what I love about the language, but here they have somehow ignored that. – Johncl Jan 10 '23 at 17:41
0

No, there isn’t an equivalent. Even in a non-module, let, const, and class declarations don’t become properties of the global object or any other object.

(This is a good thing, though! Explicit is better than implicit.)

Ry-
  • 218,210
  • 55
  • 464
  • 476