0

This is how I wrap all my JavaScript:

;(function($, window, undefined) {
    var document = window.document;
    var myFunction = function() {}
})(jQuery, window);

But now I have the need to call myFunction from outside of that closure.

window.addEventListener("offline", function(e) {
    myFunction();
}, false);

Q: How do I name the self executing anonymous function so that I can call myFunction from the global scope?

3
  • "name the self executing anonymous function", wouldn't that make it not anonymous? Commented Mar 27, 2013 at 17:33
  • Yes, it would. I don't know what I'm talking about. Commented Mar 27, 2013 at 17:34
  • Do you know that if you don't put var when declaring a variable in js, this put it in the global object? This would make it available from anywhere Commented Mar 27, 2013 at 17:35

3 Answers 3

2

Assign the function to a property of whichever object/scope you want to use.

;(function($, window, undefined) {
    var document = window.document;
    var myFunction = function() {};
    window.myFunction = myFunction;
})(jQuery, window);

You'd preferably want to return something from your IIFE that encapsulates all your 'exports' though.

var exports = (function($, window, undefined) {
    var document = window.document;
    var myFunction = function() {};
    return {
        "myFunction": myFunction
    };
})(jQuery, window);

window.addEventListener("offline", function(e) {
    exports.myFunction();
}, false);

AMD is helpful for this style of programming.

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

1 Comment

Thanks Paul. I see you're from Sheffield. I used to listen to Boagworld all the time.
2

Pretty easy, just attach your function to the global object (window):

;(function($, window, undefined) {
    var document = window.document;
    var myFunction = function() {}
    window.myNamedFunction = myFunction;
})(jQuery, window);

Comments

1

Use a namespace and push that to the global scope.

window.yourNamespace = window.yourNamespace || {};
window.yourNamespace.myFunction = function() {};

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.