# Object export in modules via closures in JavaScript

Let's say we have the following module:

`;(function() { function func1() { alert('a module function'); } function func2() { alert('a module function'); } function func3() { alert('a module function'); } })();`

Let's say we want to export all three functions to the outside. In this case, in order not to produce unnecessary function names outside the module, it is better to write all the functions into one object and export this object:

`;(function() { function func1() { alert('a module function'); } function func2() { alert('a module function'); } function func3() { alert('a module function'); } window.module = {func1: func1, func2: func2, func3: func3}; })();`

Since the names of keys and variables are the same, the object with functions code can be simplified:

`;(function() { function func1() { alert('a module function'); } function func2() { alert('a module function'); } function func3() { alert('a module function'); } window.module = {func1, func2, func3}; })();`

You can also go the other way. We will write functions to the object immediately when describing the function, like this:

`;(function() { let module = {}; module.func1 = function() { alert('a module function'); } module.func2 = function() { alert('a module function'); } module.func3 = function() { alert('a module function'); } window.module = module; })();`

Given the following module:

`;(function() { let str1 = 'a module variable'; let str2 = 'a module variable'; let str3 = 'a module variable'; function func1() { alert('a module function'); } function func2() { alert('a module function'); } function func3() { alert('a module function'); } function func4() { alert('a module function'); } function func5() { alert('a module function'); } })();`

Export the object with the first five functions and the first two variables to the outside.

← →
↑
en ru