什么是闭包和回调?
JavaScript 中的闭包和回调是什么?我还没有找到一个很好的解释。
What are closures and callbacks in JavaScript? I've yet to find a good explanation of either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
闭包已经在 Stackoverflow 中得到了很好的处理,这里只是一个选择:-
JavaScript 闭包是如何工作的?
JavaScript 中的“closure”到底指什么?< br>
你能说这是 Javascript Closure 的正确示例吗?我们需要考虑避免闭包的地方在哪里?
JavaScript 作用域和闭包
Javascript 闭包和“this”上下文
JavaScript - 如何了解“闭包”的用法?
回调是一个更简单的概念。回调基本上是一个函数接受另一个函数作为参数的地方。在执行过程中的某个时刻,被调用的函数将执行作为参数传递的函数,这是一个回调。通常,回调实际上作为异步事件发生,在这种情况下,被调用的函数可能会在没有执行回调的情况下返回,这可能会在稍后发生。这是一个常见的(基于浏览器的)示例:-
这里函数
fn
作为回调传递给setTimeout
函数。设置超时立即返回,但 5 秒后,作为回调传递的函数将被执行。闭包和回调
通常,创建闭包的原因(无论是偶然、意外还是故意)是需要创建回调。例如:-(
请阅读一些链接的帖子以掌握闭包)
创建一个闭包,其中部分包含
message
参数,fn
在调用后执行相当长的一段时间toAlertThisLater
已返回,但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:-
Here the function
fn
is passed as a callback to thesetTimeout
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:-
(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 toAlertThisLater
has returned, yetfn
still has access to the original content ofmessage
.