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

查看:18
本文介绍了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?

我不是在寻找一揽子声明闭包使代码更安全",而是在寻找回调是正确想法的实际示例列表或经验法则.

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.

克罗克福德的演讲:http://www.yuiblog.com/blog/2010/04/08/video-crockonjs-5/

推荐答案

首先:

  • 回调:作为参数传递给另一个函数的函数,通常作为事件发生的结果被调用.
  • Closure:保留的范围.IE.当你在另一个函数中声明一个函数时,外部函数的作用域可以在内部函数中访问.
  • 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 the 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 );
    };
}

那行不通.到元素被点击时,变量 i99.为了使其正常工作,我们可以使用闭包来捕获 i 的值:

That wouldn't work. By the time the element is clicked, the variable i is 99. To make this work properly we could 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天全站免登陆