Skip to content

Instantly share code, notes, and snippets.

@timhodson
Last active November 16, 2016 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timhodson/d9eee8f7bf5326ca2dacc94c066c2792 to your computer and use it in GitHub Desktop.
Save timhodson/d9eee8f7bf5326ca2dacc94c066c2792 to your computer and use it in GitHub Desktop.
IIFE Javascript Immediately-Invoked Function Expression and passing jQuery
/**
* Basic IIFE construction is like this.
*/
(function () { console.log('hello world')})();
/**
* Basic IIFE which passes in the jQuery object as the $ symbol.
*/
(function ($) { $('div.classname')})(jQuery);
/**
* Basic IIFE combined with document ready jQuery idiom.
* Assumes you have already loaded jQuery
*/
(function ($) {
/**
* set some variables.
* These will only be available to functions within the scope of the IIFE.
* No danger of redefining variables with names that might be used elsewhere
* You might use this to set max execution times, or maximum loop counts etc.
*/
var someVariable = 'Hello World!';
/**
* Setup some functions to do stuff
* Again, these are only available within the IIFE scope.
* No danger of redefining similar named functions that might be used elsewhere
*/
var callAFunction = function(){
// do something...
console.log(someVariable);
};
$(document).ready(function(){
// do some stuff here when the page has loaded.
callAFunction();
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment