Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  59] [ 2]  / answers: 1 / hits: 24157  / 15 Years ago, fri, january 15, 2010, 12:00:00

What are closures and callbacks in JavaScript? I've yet to find a good explanation of either.


More From » callback

 Answers
91

Closures have already been well handled in Stackoverflow here is just a selection:-



How does a javascript closure work?

What exactly does “closure” refer to in JavaScript?

can you say this is a right example of Javascript Closure.. Where the places we need to consider avoiding the closures??

JavaScript scope and closure

Javascript Closures and ‘this’ context

JavaScript - How do I learn about “closures” usage?



Callbacks are a simpler concept. A callback is basically where a function accepts another function as a parameter. At some point during execution the called function will execute the function passed as a parameter, this is a callback. Quite often the callback actually happens as an asynchronous event, in which case the called function may return without having executed the callback, that may happen later. Here is a common (browser based) example:-



 function fn() { alert(Hello, World); }
window.setTimeout(fn, 5000);


Here the function fn is passed as a callback to the setTimeout function. Set timeout returns immediately however 5 seconds later the function passed as a callback is executed.



Closures and callbacks



Quite often the reason that closures get created (either incidentally, accidentally or deliberately) is the need to create a callback. For example:-



 function AlertThisLater(message, timeout)
{
function fn() { alert(message); }
window.setTimeout(fn, timeout);
}

AlertThisLater(Hello, World!, 5000);


(Please read some of the linked posts to grasp closures)



A closure is created containing in part the message parameter, fn is executed quite some time after the call to AlertThisLater has returned, yet fn still has access to the original content of message.


[#97824] Tuesday, January 12, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mercedez

Total Points: 525
Total Questions: 103
Total Answers: 102

Location: Trinidad and Tobago
Member since Fri, Mar 24, 2023
1 Year ago
;