回调函数的有用性 [英] Usefulness of callback functions

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

问题描述

在Javascript中,可以定义一个函数X,并将其作为参数传递给另一个函数Y.



这样的函数X被称为 callback function



您能解释为什么在一些清楚的例子中使用回调函数)?我可以看到一个有用的东西,它的代码可读性,但我不确定在这,因为代码与回调看起来更复杂。



唯一的有用的是它在浏览器环境和异步执行在AJAX?
关于其他Javascript实现(例如 Rhino )?回调在那里有用吗?



谢谢

解决方案

回调作为参数



回调是非常有用的,因为它们允许您使用代码配置 >

这个原型的例子是一个排序函数,它允许你指定你自己的排序标准。我将使用一个函数,返回一个数组的最小值基于一些标准,因为它比一个排序更简单,但它仍然可以作为一个例证:

  function min(collection,property){
if(collection.length == 0){
return null;
}

var minIndex = 0;
var minValue = collection [0] [property];
for(var i = 1; i if(minValue> collection [i] [property]){
minValue = collection [i ][属性];
minIndex = i;
}
}

return collection [minIndex];
}

var items = [
{name:John,age:20},{name:Mary,age:18}
];

alert(min(items,'age')。name); // printsMary

查看此代码运行 问题是什么?



问题是,虽然我们努力创建一个可配置的 min 函数(它根据我们指定的任何属性找到最小值),但是它在一般意义上仍然相当有限,因为它只能根据一个单一属性找到最小值。



$ b

如果我们的数据是这样的,该怎么办?

  var items = [John / 20,Mary / 18]; 

这不再是一个对象数组,而是一个格式化字符串数组。它具有与原始集合相同的数据,但在不同的结构中。因此,不能使用原始的 min 函数来处理它。



现在我们可以写另一个版本 min 使用字符串而不是对象,但这将是无意义的(有无限多种方式来表示相同的数据)。对于一种特定情况,这可能是一个快速和肮脏的解决方案,但是考虑库编写器的问题: :他们如何编写一个对每个人有用的函数,而不知道如何结构化数据



简单:使<$>通过允许其用户指定如何从数据中提取条件,c $ c> min 函数更强大。这听起来很像给出函数代码从数据中提取标准,这是我们要做的。 min 将接受回呼

  function min(collection,callback){
if(collection.length == 0){
return null;
}

var minIndex = 0;
var minValue = callback(collection [0]);
for(var i = 1; i if(minValue> callback(collection [i])){
minValue = callback [一世]);
minIndex = i;
}
}

return collection [minIndex];
}

var items = [John / 20,Mary / 18];

var minItem = min(items,function(item){
return item.split('/')[1]; //获取age部分
} );

alert(minItem);

查看此代码运行



现在我们的代码可重复使用。我们可以轻松地将其配置为使用第一个第二种类型的数据。



查看回调启用的函数处理这两种类型的数据 。这是我们通过允许用户以回调的形式提供代码作为函数的一部分运行而获得的极端灵活性的结果。



异步编程中的回调



回调的另一个主要用途是启用异步编程模型。这在您计划完成某个操作,但不希望您的程序在操作完成之前停止运行的所有情况下都很有用。



为了使其正常工作,你为操作提供一个回调函数并有效地告诉它:去做这个工作给我,当你完成后,回电话。然后你可以自由地做任何你喜欢的事情,知道当结果可用时,你指定的函数将运行。



这是最可见的在web AJAX:您向网络服务器发出请求,并且在收到响应时 您以某种方式对其进行操作。你不想在现场等待响应,因为它可能需要很多时间(例如,如果有连接问题),并且你不希望你的程序在这段时间内无响应。



有关AJAX回调的示例,请参阅jQuery的文档 load 函数。


In Javascript there is a possibility to define a function X and pass it as an argument to another function Y.

Such a function X is called a callback function.

Could you explain why is useful to use callback functions in some clear examples (e.g. send some fiddle links with demonstration)? I can see one usefulness, it's code readability, but I'm not sure in this, because code with callbacks looks more complex.

The only usefulness is it's use in browser environment and asynchronous execution in AJAX? What about another Javascript implementations (e.g. Rhino)? Are callbacks useful there as well? Or does their usefulness depend only on the environment where Javascript is executed?

thank you

解决方案

Callbacks as parameters

Callbacks are useful because they allow you to "configure" a function with code.

The archetypal example for this is a sorting function which allows you to specify your own sort criteria. I 'm going to use a function that returns the minimum value of an array based on some criteria because it's simpler than a sort, but it still will serve fine as an illustration:

function min(collection, property) {
    if (collection.length == 0) {
        return null;
    }

    var minIndex = 0;
    var minValue = collection[0][property];
    for (var i = 1; i < collection.length; ++i) {
        if (minValue > collection[i][property]) {
            minValue = collection[i][property];
            minIndex = i;
        }
    }

    return collection[minIndex];
}

var items = [
    { name: "John", age: 20 }, { name: "Mary", age: 18 }
    ];

alert(min(items, 'age').name); // prints "Mary"

See this code run. What is the problem with it?

The problem is that while we made some effort in order to create a configurable min function (it finds the minimum based on any property we specify), it's still pretty limited in the general sense because it can only find the minimum based on one single property.

What if our data was like this?

var items = [ "John/20", "Mary/18" ];

This is no longer an array of objects, but an array of formatted strings. It has the same data as the original collections, but in a different structure. As a result, the original min function cannot be used to process it.

Now we could write another version of min that works with strings instead of objects, but that would be kind of pointless (there are infinitely many ways to represent the same data). This might be OK as a quick and dirty solution for one particular case, but consider the problem of a library writer: how could they write one function useful to everyone, without knowing how the data will be structured in each case?

Callbacks to the rescue

Simple: make the min function more powerful by allowing its user to specify how to extract the criteria from the data. This sounds very much like "giving the function code to extract the criteria from the data", which is what we are going to do. min will accept a callback:

function min(collection, callback) {
    if (collection.length == 0) {
        return null;
    }

    var minIndex = 0;
    var minValue = callback(collection[0]);
    for (var i = 1; i < collection.length; ++i) {
        if (minValue > callback(collection[i])) {
            minValue = callback(collection[i]);
            minIndex = i;
        }
    }

    return collection[minIndex];
}

var items = [ "John/20", "Mary/18" ];

var minItem = min(items, function(item) {
    return item.split('/')[1]; // get the "age" part
});

alert(minItem);

See this code run.

Now at last our code is reusable. We can easily configure it to work both with the first and the second type of data with minimal effort.

See the callback-enabled function handle both types of data. This is the result of the extreme flexibility we gained as a result of allowing the user to provide code to run as part of our function, in the form of a callback.

Callbacks in asynchronous programming

Another major use of callbacks is to enable asynchronous programming models. This is useful in all cases where you schedule an operation to complete, but do not want your program to stop running until the operation has completed.

In order for this to work, you provide the operation with a callback function and effectively tell it: go do this work for me, and when you are done, call me back. You are then free to go ahead and do anything you like, knowing that when the results are available the function you specified will run.

This is most visible in the web with AJAX: you fire off a request to a web server, and when the response has been received you act upon it in some manner. You don't want to wait on the spot for the response because it might take a lot of time (e.g. if there are connection problems) and you don't want your program to be unresponsive for all that time.

For an example of an AJAX callback, see the documentation for the jQuery load function.

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

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