Skip to content

Instantly share code, notes, and snippets.

View domfarolino's full-sized avatar

Dominic Farolino domfarolino

View GitHub Profile

The point of a closure is to create an outer function that can act like a factory. This factory function produces other smaller functions (an inner function inside the outer factory function). Now before I go on, let's remember that the inner function (against intuition and assisted by the language itself) IS TOTALLY allowed to safely use the local state of the outer function. This works properly even when the outer function's state is removed from the stack, and disappears.

This is the key to closures, and to take proper advantage of it we really only want to call the factory function (outer function) when we want to produce an inner function that depends on a local state that the outer function provides. So let's use a suuuppper simple example.

Consider this JavaScript code:

var outerFunction = function(outerFunctionState) {

  var innerFunction = function() {
@domfarolino
domfarolino / closure3.js
Created September 23, 2016 20:32
3rd example explaining closures to Pat
var stopWatchBuilder = function() {
var outerFunctionState = Date.now();
var innerFunction = function() {
console.log("Time difference: " + (Date.now() - outerFunctionState)/1000);
}
return innerFunction;
}
@domfarolino
domfarolino / closure2.js
Created September 23, 2016 20:28
2nd example explaining closures to Pat
var outerFunction = function(outerFunctionState) {
var innerFunction = function() {
console.log("Time difference: " + (Date.now() - outerFunctionState)/1000);
}
return innerFunction;
}
var generatedFunction1 = outerFunction(Date.now());
@domfarolino
domfarolino / closure1.js
Created September 23, 2016 20:16
1st example explaining closures to Pat
var outerFunction = function(outerFunctionState) {
var innerFunction = function() {
console.log("Snapshot of the outerFunction's state is: " + outerFunctionState);
}
return innerFunction;
}
var generatedFunction1 = outerFunction(5);