Skip to content

Instantly share code, notes, and snippets.

@karlpokus
Created July 7, 2016 06:09
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 karlpokus/ebc35704b5d17cde33ac8243011cc2cb to your computer and use it in GitHub Desktop.
Save karlpokus/ebc35704b5d17cde33ac8243011cc2cb to your computer and use it in GitHub Desktop.
IIFE - modular pattern in JS
// from http://appendto.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
(function(foo, $, undefined){ // parameters
// private var in closure
var data = [1, 2, 3];
// public fn
foo.moo = function() {
console.log(data);
}
return foo;
})(window.foo = window.foo || {}, jQuery); // args
// calls itself immediately
// uses args from global scope
// refers to named parameters
// use $ and be sure it's jQuery
// undefined is used as 3rd param to assure it's not rewritten by other code in global scope. This sets undefineds value to undefined as it lacks an corresponding arg.
// *******
// PATTERNS
// *******
// 1. simple iife
// - all private
// 2. revealing module pattern
// - assign a return to a var
// - ok to set more public methods later
// 3. iife public and private
// - set props on object passed in
// - ok to set more public methods later
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment