Javascript 什么是闭包和回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2070275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:39:23  来源:igfitidea点击:

What are Closures and Callbacks?

javascriptcallbackclosures

提问by AnthonyWJones

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

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

回答by AnthonyWJones

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

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

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?

javascript 闭包是如何工作的?
JavaScript 中的“闭包”究竟指的是什么?
你能说这是 Javascript Closure 的一个正确例子.. 我们需要考虑避免闭包的地方在哪里??
JavaScript 范围和闭包
Javascript 闭包和“this”上下文
JavaScript - 我如何了解“闭包”的用法?

Callbacksare 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 fnis passed as a callbackto the setTimeoutfunction. Set timeout returns immediately however 5 seconds later the function passed as a callbackis executed.

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

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 messageparameter, fnis executed quite some time after the call to AlertThisLaterhas returned, yet fnstill has access to the original content of message.

创建一个包含部分message参数的闭包,fn在调用AlertThisLater返回后执行一段时间,但fn仍然可以访问message.