Equivalent of a window object in JavaScript modules?

Viewed 28

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.

2 Answers

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.)

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.

Related