Exporting an Object in Modules via Closures in JavaScript
Let's say we have the following module:
;(function() {
function func1() {
alert('module funcion');
}
function func2() {
alert('module funcion');
}
function func3() {
alert('module funcion');
}
})();
Let's say we want to export all three functions externally. In this case, to avoid cluttering the outside of the module with extra function names, it's better to place all the functions into a single object and export that object:
;(function() {
function func1() {
alert('module funcion');
}
function func2() {
alert('module funcion');
}
function func3() {
alert('module funcion');
}
window.module = {func1: func1, func2: func2, func3: func3};
})();
Since the key names and variable names match, the object with functions can be simplified:
;(function() {
function func1() {
alert('module funcion');
}
function func2() {
alert('module funcion');
}
function func3() {
alert('module funcion');
}
window.module = {func1, func2, func3};
})();
Another approach is also possible. We can assign the functions to the object immediately when declaring them, like this:
;(function() {
let module = {};
module.func1 = function() {
alert('module funcion');
}
module.func2 = function() {
alert('module funcion');
}
module.func3 = function() {
alert('module funcion');
}
window.module = module;
})();
Given the following module:
;(function() {
let str1 = 'module variable';
let str2 = 'module variable';
let str3 = 'module variable';
function func1() {
alert('module funcion');
}
function func2() {
alert('module funcion');
}
function func3() {
alert('module funcion');
}
function func4() {
alert('module funcion');
}
function func5() {
alert('module funcion');
}
})();
Export an object containing the first five functions and the first two variables externally.