Search code examples
javascriptself-executing-function

Define global function within anonymous self-executing function?


(function(){

  var someValue = 5;

  function myFunction(input) = {
    return someValue * input;
  };

})();

I have a self-executing function, that contains many things, among them at function that I would like to make global. I would typically just declare it in the global scope, but it needs to be able to reference variables that are local only to the self-executing function.

What is the best approach to making the function globally-accessible without getting rid of the self-executing function altogether (thus littering the global space with variables)?


Solution

  • You can add the function to the global window object.

    (function(){
    
      var someValue = 5;
    
      window.myFunction = function (input) {
        return someValue * input;
      };
    
    })();
    

    After the immediate function executed, you can call myFunction().