Created
July 7, 2016 06:09
-
-
Save karlpokus/ebc35704b5d17cde33ac8243011cc2cb to your computer and use it in GitHub Desktop.
IIFE - modular pattern in JS
This file contains hidden or 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
// 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