Last active
November 16, 2016 13:28
-
-
Save timhodson/d9eee8f7bf5326ca2dacc94c066c2792 to your computer and use it in GitHub Desktop.
IIFE Javascript Immediately-Invoked Function Expression and passing jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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