1
(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 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.