什么是闭包和回调?

发布于 2024-08-17 22:35:36 字数 43 浏览 3 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

林空鹿饮溪 2024-08-24 22:35:36

闭包已经在 Stackoverflow 中得到了很好的处理,这里只是一个选择:-

JavaScript 闭包是如何工作的?
JavaScript 中的“closure”到底指什么?< br>
你能说这是 Javascript Closure 的正确示例吗?我们需要考虑避免闭包的地方在哪里?
JavaScript 作用域和闭包
Javascript 闭包和“this”上下文
JavaScript - 如何了解“闭包”的用法?

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

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

这里函数 fn 作为回调传递给 setTimeout 函数。设置超时立即返回,但 5 秒后,作为回调传递的函数将被执行。

闭包和回调

通常,创建闭包的原因(无论是偶然、意外还是故意)是需要创建回调。例如:-(

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

 AlertThisLater("Hello, World!", 5000);

请阅读一些链接的帖子以掌握闭包)

创建一个闭包,其中部分包含 message 参数,fn 在调用后执行相当长的一段时间to AlertThisLater 已返回,但 fn 仍然可以访问 message 的原始内容。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文