3

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 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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 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.
Thank you. I wasn't getting it, of course; but seem to understand now.
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.
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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.