Javascript:闭包和回调 [英] Javascript: Closures and Callbacks

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

问题描述

这两个是什么?我还没有找到一个很好的解释。

解决方案

关闭在Stackoverflow这里只是一个选择: -



JavaScript关闭如何工作?

闭包在JavaScript中指的是什么?



JavaScript范围和关闭

JavaScript关闭和此上下文

JavaScript - 如何了解关闭用法?



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

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

这里函数 fn 回调 setTimeout 函数。



关闭和回调 / p>

很多时候,创建闭包的原因(偶然的,偶然的或有意的)是需要创建一个回调。例如: -

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

AlertThisLater(Hello,World!,5000);

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



创建一个闭包,部分包含消息参数, fn 已返回对 AlertThisLater 的调用,但 fn 仍可访问消息的原始内容


What are these two? I've yet to find a good explanation of either.

解决方案

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.

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

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