Define global function within anonymous self-executing function?

321 Views Asked by At
(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)?

2

There are 2 best solutions below

0
On BEST ANSWER

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().

0
On

Alternatively, you could do something like this, which has essentially the same result that ntalbs proposed.

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

console.log( myFunction( 4 ), window.myFunction ); // output: 20, function(input){return someValue * input}