I was listening to Crockford's talk on JavaScript closures and am convinced of the benefit of information hiding, but I do not have a firm understanding of when to use callback functions.
It is mostly a true statement that a person could accomplish the same functionality with or without callbacks.
As someone who is writing code, what heuristics or cues should I keep in mind when determining when to use callbacks/closures?
I am not looking for the blanket statement 'Closures make more secure code', rather a list of practical examples or rules of thumb for when callbacks are the right idea.
Crockford's Presentation: http://www.yuiblog.com/blog/2010/04/08/video-crockonjs-5/
A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.
A closure is when a function has access to variables (can read and change them) defined in its outer scope, even when the function is executed outside of the scope where it was defined. A closure is a function enclosing a reference (variable) to its outer scope. Functions can access variables outside of their scope.
a callback is executable code that is passed as an argument to other code. Closure - a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables.
Firstly:
Callbacks can also be closures but are not always.
This is a callback:
someProcess(myCallback); function myCallback() { alert('Done...'); } function someProcess(callback) { // does stuff... // ... callback(); }
A closure:
function foo(msg) { function bar() { // I can access foo's scope // (i.e. bar can access everything that foo can access) alert(msg); } return bar; } foo('hello')(); // alerts "hello"
One common usage of closures is to provide information-hiding, which is helpful in bringing some kind of encapsulation to the language. Have a look at the module pattern to see this in action.
Another common usage is when the binding event handlers to elements. E.g.
var myElements = [ /* DOM Collection */ ]; for (var i = 0; i < 100; ++i) { myElements[i].onclick = function() { alert( 'You clicked on: ' + i ); }; }
That wouldn't work. By the time the element is clicked, the variable i
is 99
. To make this work properly we could use a closure to capture the value of i
:
function getHandler(n) { return function() { alert( 'You clicked on: ' + n ); }; } for (var i = 0; i < 100; ++i) { myElements[i].onclick = getHandler(i); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With