Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a closure different from a callback?

I asked a question about callbacks and arrived at another question (see comment). How is a closure different from a callback?

like image 981
leeand00 Avatar asked Mar 05 '09 18:03

leeand00


People also ask

What is the difference between closure and callback?

a callback is executable code that is passed as an argument to other code. 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. a callback is executable code that is passed as an argument to other code.

Is callback an example of closure?

Callbacks are also closures as the passed function is executed inside other function just as if the callback were defined in the containing function.

What is the difference between events and callback?

Callback is for asking another function to do business operations and send a result whereas events are not but asking for handover the control so that we can only handle business operation. Eg: Button click is event (We are doing business operation on click of button).

What is the purpose of a closure?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.


2 Answers

Check the introduction in this: http://jibbering.com/faq/faq_notes/closures.html. It can help you understand better how closures relate to functions.

Here is a set of closure examples: http://www.javascriptkit.com/javatutors/closures2.shtml

Basically, the callback is like a function pointer. The bit that makes it a closure, is when that function accesses anything on the context where it lives, like variables outside it. When that happens, the function will use the current values of the variables (as opposed to copy them). See example 4.

like image 192
eglasius Avatar answered Sep 28 '22 03:09

eglasius


Different definitions:

Callback -

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.

like image 36
gimel Avatar answered Sep 28 '22 04:09

gimel