Warm tip: This article is reproduced from stackoverflow.com, please click
ecmascript-6 javascript module namespaces

ECMAScript Modules vs objects-as-namespaces

发布于 2020-03-27 10:22:29

I've been using Modules that are presented with ES6 for a while. While I (instinctively) know that it is better to use them, I struggle to explain why.

With modules;

  • I can do dependency declaration (not injection). I do not have to use a script tag for each javascript file I load.
  • Before modules, objects served as namespaces. Now that we have modules, we have namespaces which is a better paradigm for code organization.

Else than this, why should I use modules ?

What advantage they provide over just using objects as namespaces ?

EDIT:

Thanks to the comments of Bergi and Randy Casburn, I am now able to point out two more things.

  • With Module Pattern(which i been calling object-as-namespaces) we have same functionality. But we get it through closures. In Modules, we have separate files. Features of a separate file is harder to be violated.

  • Modules hide their internal features. It drives us towards thinking about better software design.

Questioner
Doruk
Viewed
53
Doruk 2019-07-03 22:22

Answering my own question. Thanks for the comments.

  • Modularity is a must for software. Before ES Modules, we achieved modules through Module Pattern(which is simply putting related things in an object). By ES6, Modules are native. And native is always the better option.

  • In Module Pattern, we made modules with closures. In ES Modules we code them in seperate files.

    • Seperate files adds another layer of protection against code violation.
  • Modules drive us to design better software.

    • With ES Modules we have export keyword which gives us freedom to choose what to expose.
    • We also have import keyword to pick whatever we want from a module.
  • With ES6 Modules we can now include Javascript modules which are in seperate files into our web app without the need to include them in script tags.