Skip to content

Instantly share code, notes, and snippets.

@harrylove
Created September 20, 2011 20:52
Show Gist options
  • Save harrylove/1230292 to your computer and use it in GitHub Desktop.
Save harrylove/1230292 to your computer and use it in GitHub Desktop.
Fun with JavaScript closures
console.info('* TRUTH *');
var truth = function() { return true; };
console.info(truth); // function()
console.info(truth()); // true
console.info('* F *');
var origF = function(arg) { return arg; };
var f = origF;
console.info(f); // function()
console.info(f()); // undefined
console.info(f(truth)); // function()
console.info(f(truth())); // true
console.info('* G *');
// Uncommenting the console lines inside this function will give you a hint as to what's happening
var g = function(func) {
//console.info('the outer arguments are', arguments);
return function() {
//console.info('the inner arguments are', arguments);
return func();
};
}
console.info(g); // function()
console.info(g()); // function()
console.info(g('hello')); // function()
try {
g('hello')();
} catch (e) {
console.info(e); // TypeError: func is not a function
}
console.info(g(truth)); // function()
console.info(g(truth)()); // true
console.info('* H *');
var h = g(truth);
console.info(h); // function()
console.info(h()); // true
// And the kickers
console.info('* F again *');
f = g(f);
console.info(f); // function()
console.info(f()); // undefined
console.info(f(truth)) // undefined
// reset f
f = origF;
f = g(f(truth));
console.info(f); // function()
console.info(f()); // true
console.info(f(truth)) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment