Exportera ett objekt i moduler genom closures i JavaScript
Låt oss säga att vi har följande modul:
;(function() {
function func1() {
alert('module function');
}
function func2() {
alert('module function');
}
function func3() {
alert('module function');
}
})();
Låt oss säga att vi vill exportera alla tre funktioner. I det här fallet, för att inte skapa för många funktionsnamn utanför modulen, är det bättre att lägga alla funktioner i ett objekt och exportera det objektet:
;(function() {
function func1() {
alert('module function');
}
function func2() {
alert('module function');
}
function func3() {
alert('module function');
}
window.module = {func1: func1, func2: func2, func3: func3};
})();
Eftersom nyckelnamnen och variabelnamnen är desamma, kan objektet med funktioner förenklas:
;(function() {
function func1() {
alert('module function');
}
function func2() {
alert('module function');
}
function func3() {
alert('module function');
}
window.module = {func1, func2, func3};
})();
Man kan också gå tillväga på ett annat sätt. Vi lägger funktionerna i objektet direkt när funktionen definieras, så här:
;(function() {
let module = {};
module.func1 = function() {
alert('module function');
}
module.func2 = function() {
alert('module function');
}
module.func3 = function() {
alert('module function');
}
window.module = module;
})();
Följande modul är given:
;(function() {
let str1 = 'module variable';
let str2 = 'module variable';
let str3 = 'module variable';
function func1() {
alert('module function');
}
function func2() {
alert('module function');
}
function func3() {
alert('module function');
}
function func4() {
alert('module function');
}
function func5() {
alert('module function');
}
})();
Exportera ett objekt med de första fem funktionerna och de första två variablerna.