Skip to content

Instantly share code, notes, and snippets.

@stormwild
Created December 8, 2012 02:50
Show Gist options
  • Save stormwild/4238330 to your computer and use it in GitHub Desktop.
Save stormwild/4238330 to your computer and use it in GitHub Desktop.
Immediately-Invoked Function Expression (IIFE) / (jQuery Self Executing Closure Pattern) and other useful javascript snippets
// “self-executing anonymous function” (or self-invoked anonymous function)
// Reference: http://stackoverflow.com/questions/188663/jquery-javascript-design-self-executing-function-or-object-literal
;(function($) {
var myPrivateFunction = function() {
};
var init = function() {
myPrivateFunction();
};
$(init);
})(jQuery);
// http://benalman.com/news/2010/11/immediately-invoked-function-expression/
// Immediately-Invoked Function Expression (IIFE)
// Either of the following two patterns can be used to immediately invoke
// a function expression, utilizing the function's execution context to
// create "privacy."
(function(){ /* code */ }()); // Crockford recommends this one
(function(){ /* code */ })(); // But this one works just as well
// Pactpub.KnockoutJS.Starter.Nov.2012
// Define the namespace
window.myApp = {};
(function(myApp) {
// Product Constructor Function
function Product() {
var self = this;
// "SKU" property
self.sku = ko.observable("");
// "Description" property
self.description = ko.observable("");
// "Price" property
self.price = ko.observable(0.00);
// "Cost" property
self.cost = ko.observable(0.00);
// "Quantity" property
self.quantity = ko.observable(0);
}
// add to our namespace
myApp.Product = Product;
}(window.myApp));
// Usage
// create an instance of the Product class
var productA = new myApp.Product();
// "set" the 'sku' property
productA.sku('12345')
// "get" the 'sku' property value
var skuNumber = productA.sku();
// Products ViewModel
(function(myApp) {
// constructor function
function ProductsViewModel() {
var self = this;
// the product that we want to view/edit
self.selectedProduct = ko.observable();
}
// add our ViewModel to the public namespace
myApp.ProductsViewModel = ProductsViewModel;
}(window.myApp));
// http://skilldrick.co.uk/2011/04/closures-explained-with-javascript/
function f(x) {
function g() {
return x;
}
return g;
}
//Tell f to create a new g
var g5 = f(5);
//g5 is a function that always returns 5
alert(g5());
//Tell f to create another new g
var g1 = f(1);
//g1 is a function that always returns 1
alert(g1());
function person(name) {
function get() {
return name;
}
function set(newName) {
name = newName;
}
return [get, set];
}
var getSetDave = person('Dave');
var getDave = getSetDave[0];
var setDave = getSetDave[1];
alert(getDave()); //'Dave'
setDave('Bob');
alert(getDave()); //'Bob'
var getSetMary = person('Mary');
var getMary = getSetMary[0];
var setMary = getSetMary[1];
alert(getMary()); //'Mary'
@stormwild
Copy link
Author

$(init);

$(document).ready(function(){ ... }); 

$(function() {}); 

Reference: http://stackoverflow.com/questions/3259496/jquery-document-ready-vs-self-calling-anonymous-function

$(document).ready(function(){ ... }); or short $(function(){...});

This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.

(function(){ ... })();

That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your ecma-/javascript. Therefor, its very unlikely that you can successfully act on DOM elements here.


// My comments
Which is maybe why scripts which contain self executing functions are linked at the bottom of the page to help ensure that the rest of the page has loaded? Is this a valid statement?

@stormwild
Copy link
Author

You can also pass window to the IIFE

(function(window, undefined){
    function myApp () {
      // class body here
    }

    window.myApp = myApp; // available globally through window
})(window);

@stormwild
Copy link
Author

http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/#question-about-surrounding-parentheses

Another example is creation of encapsulated scope to hide auxiliary helper data from external context (in the following example we use FE which is called right after creation):

var foo = {};

(function initialize() {

  var x = 10;

  foo.bar = function () {
    alert(x);
  };

})();

foo.bar(); // 10;

alert(x); // "x" is not defined

We see that function foo.bar (via its [[Scope]] property) has access to the internal variable x of function initialize. And at the same time x is not accessible directly from the outside. This strategy is used in many libraries to create “private” data and hide auxiliary entities. Often in this pattern the name of initializing FE is omitted:

@stormwild
Copy link
Author

Why does window have to be passed to a function expression when window is global object and should be accessible from within a function?

http://stackoverflow.com/questions/8275658/passing-window-and-undefined-to-an-immediately-invoked-anonymous-function-why

Micro optimisation.

Having window as a local variable is marginally faster than a global variable.

It also minifies better. We can now minify the function parameter to w and use w.setTimeout etc instead of window.setTimeout.

Fewer bytes = better

http://stackoverflow.com/questions/6400632/why-do-we-need-to-pass-in-window-and-undefined-into-this-jquery-plugin

10 Things I Learned from the jQuery Source
http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
http://www.youtube.com/watch?v=i_qE1iAmjFg

@stormwild
Copy link
Author

jQuery equivalent of JavaScript's addEventListener method
http://stackoverflow.com/questions/2398099/jquery-equivalent-of-javascripts-addeventlistener-method

As of jQuery 1.7, .on() is now the preferred method of binding events, rather than .bind():

From http://api.jquery.com/bind/:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
The documentation page is located at http://api.jquery.com/on/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment