How is a closure different from a callback?

2019-01-16 11:31发布

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

9条回答
Ridiculous、
2楼-- · 2019-01-16 12:13

Here is a way to differentiate between those two:

Closure

A Closure is used to extend functionality, for instance if a user clicks a button, we want something to happen on the screen, in that case, we would use a Closure where we pass the user event (a click) and then push data to the view.

Callback

A callback is more or less similar to a closure, but it is more used to inform and provide synchronous capabilities. For instance if you perform jQuery Ajax calls, you'll have callbacks such as success(), error(), beforeSend() and so forth to handle the asynchronous data.

查看更多
Evening l夕情丶
3楼-- · 2019-01-16 12:15

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.

查看更多
叼着烟拽天下
4楼-- · 2019-01-16 12:16

I fail to see how the two are even related? A closure carries parts of a local state into a function of some sort, think of it as passing by reference.

A callback is meant to notify you about certain change and it redirects program flow. The closure could modify local state but you would never get processor time to handle that, like you would with a callback.

查看更多
Bombasti
5楼-- · 2019-01-16 12:17

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.

查看更多
时光不老,我们不散
6楼-- · 2019-01-16 12:22

A callback depending on a context variable aka bound variables (== object state) will be a closure. It will be a pure function, otherwise, when it only takes free variables (== parameters).

查看更多
The star\"
7楼-- · 2019-01-16 12:24

There's a good definition of closures here:

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

In practice, that means it's a function that has some hidden variables.

A callback is a higher-level idea. Generally it is a function which is passed around with the intent of being called at a later time. In JavaScript, closures are often used as callbacks.

查看更多
登录 后发表回答