Home > Article > Web Front-end > Introduction to JS modules and namespaces_javascript skills
Cause
An important reason for organizing code into classes is to make the code more "modular" and enable code reuse in many different scenarios. But classes are not the only way to modularize code.
Generally speaking, a module is an independent JS file. A module file can contain a class definition, a set of related classes, a library of utility functions, or some code to be executed.
The goal of modularization is to support large-scale program development, handle the assembly of code from dispersed sources, and enable the code to run correctly, even if it contains unnecessary module code.
Ideally, no module should define more than one global flag.
Module function
is implemented by defining the module inside a function. The defined variables and functions are local variables of the function and are not visible outside the function. In fact, you can use this function scope as the module’s namespace (module function)
Once the module code is encapsulated into a function, you need some way to export the public API so that they can be called outside the module function. There are several ways to export public APIs:
First create a namespace
1. Use constructor
2. Return the namespace object
If the module API includes multiple units, it can return a namespace object
3. Call
through the keyword newAnother similar technique: treat module functions as constructors and call them through new. Assign them (public API) to this attribute to export them
4. Defined namespace object
As an alternative, if a global namespace object has been defined, module functions can directly set the properties of that object.
For this reason, the method of exporting public API has been explained.