JavaScript中的闭包/回调函数的用例是什么? [英] What are the use cases for closures/callback functions in JavaScript?

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

问题描述

我正在听Crockford关于JavaScript闭包的讨论,并相信信息隐藏的好处,但我并不完全了解何时使用回调函数。

I was listening to Crockford's talk on JavaScript closures and am convinced of the benefit of information hiding, but I do not have a firm understanding of when to use callback functions.

这是一个真正的声明,一个人可以完成相同的功能,有或没有回调。

It is mostly a true statement that a person could accomplish the same functionality with or without callbacks.

作为编写代码的人,我应该保持什么启发式或提示在确定何时使用回调/关闭?

As someone who is writing code, what heuristics or cues should I keep in mind when determining when to use callbacks/closures?

我不是在寻找覆盖语句Closures make更安全的代码,而是一个实用示例或规则列表

I am not looking for the blanket statement 'Closures make more secure code', rather a list of practical examples or rules of thumb for when callbacks are the right idea.

Crockford的演讲:
http://www.yuiblog.com/blog/2010/04/08/video-crockonjs-5/

Crockford's Presentation: http://www.yuiblog.com/blog/2010/04/08/video-crockonjs-5/

推荐答案

首先:


  • 回调:作为参数传递给另一个函数,通常被称为事件发生的结果。

  • 关闭:保留的范围。也就是说当您在另一个函数中声明一个函数时,外部函数的范围在函数内是可访问的。

  • Callback: A function passed as an argument to another function, usually to be called as a result of an event occurring.
  • Closure: A retained scope. I.e. the concept that when you declare a function within another function, the outer function's scope is accessible within the inner function.

回调也可以是闭包,但不总是。

Callbacks can also be closures, but are not always.

这是一个回调:

someProcess(myCallback);

function myCallback() {
    alert('Done...');
}

function someProcess(callback) {
    // does stuff...
    // ...
    callback();
}

结束:

function foo(msg) {

    function bar() {
        // I can access foo's scope
        // (i.e. bar can access everything that foo can access)
        alert(msg);
    }

    return bar;

}

foo('hello')(); // alerts "hello"

闭包的一个常见用法是提供信息隐藏在给语言带来某种封装。请查看模块模式以查看此操作。

One common usage of closures is to provide information-hiding, which is helpful in bringing some kind of encapsulation to the language. Have a look at the module pattern to see this in action.

另一种常见的用法是将事件处理程序绑定到元素。例如

Another common usage is when binding event handlers to elements. E.g.

var myElements = [ /* DOM Collection */ ];

for (var i = 0; i < 100; ++i) {
    myElements[i].onclick = function() {
        alert( 'You clicked on: ' + i );
    };
}

这不行。到该元素被点击时,变量 i 99 。为了使其正常工作,我们使用一个闭包来捕获 i 的值:

That wouldn't work. By the time the element is clicked, the variable i is 99. To make this work properly we cold use a closure to capture the value of i:

function getHandler(n) {
    return function() {
        alert( 'You clicked on: ' + n );
    };
}

for (var i = 0; i < 100; ++i) {
    myElements[i].onclick = getHandler(i);
}

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

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