Eksportere et objekt i moduler ved hjelp av lukninger i JavaScript

La oss si at vi har følgende modul:

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

La oss si at vi vil eksportere alle tre funksjonene ut. I dette tilfellet, for å unngå å lage for mange funksjonsnavn utenfor modulen, er det bedre å legge alle funksjonene i ett objekt og utføre eksport av dette objektet:

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

Siden nøkkelnavnene og variabelnavnene er like, kan objektet med funksjonene forenkles:

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

Vi kan også gå en annen vei. Vi kan legge til funksjonene i objektet direkte når vi definerer funksjonen, slik som dette:

javascript;(function() {
  let module = {};
  
  module.func1 = function() {
    alert('module function');
  }
  module.func2 = function() {
    alert('module function');
  }
  module.func3 = function() {
    alert('module function');
  }
  
  window.module = module;
})();
Задание 1

Gitt følgende modul:

javascript;(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');
  }
})();

Eksporter et objekt med de fem første funksjonene og de to første variablene ut.