什么是闭包和回调? [英] What are Closures and Callbacks?

查看:206
本文介绍了什么是闭包和回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中的闭包和回调是什么?我还没有找到一个很好的解释。

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

推荐答案

闭包已经得到妥善处理在Stackoverflow中这里只是一个选择: -

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

javascript关闭如何工作?

在JavaScript中引用闭包究竟是什么?

你能说这是一个正确的Javascript Closure示例..我们需要考虑的地方避免了关闭?

JavaScript范围和结束

Javascript Closures和'this'上下文

JavaScript - 我如何了解闭包的用法?

回调是一个更简单的概念。回调基本上是函数接受另一个函数作为参数的地方。在执行期间的某个时刻,被调用函数将执行作为参数传递的函数,这是回调。通常,回调实际上是作为异步事件发生的,在这种情况下,被调用的函数可能会在没有执行回调的情况下返回,这可能会在以后发生。这是一个常见的(基于浏览器的)示例: -

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);

此处函数 fn 作为a 回调 setTimeout 函数。设置超时立即返回,但是5秒后执行的函数作为回调执行。

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.

闭包和回调

通常需要创建一个回调来创建闭包(无论是偶然的,偶然的还是故意的)。例如: -

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)

创建一个包含部分消息参数的闭包, fn 在执行了一段时间后执行已返回 AlertThisLater 的调用,但 fn 仍然可以访问消息的原始内容

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.

这篇关于什么是闭包和回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆