可以有人解释我的回调函数? [英] Can Someone Explain me the Callback functions?

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

问题描述

我最近开始学习javascript,我看到了很多回调函数。
这些函数是什么,为什么它们被使用和为什么?
我很高兴得到真正的基本定义,因为我想知道它,因为我意识到这是真正重要的js。

I've started recently to learn about javascript, and I saw a lot of callback functions. What are those functions, why they are used and what for? I will be happy to get really basic definition, because I wanna understand it because I realised that it is really important in js.

谢谢:)


thanks :)

推荐答案

顾名思义,回调函数是作为参数传递给另一个函数或AJAX调用的匿名或命名函数。并将在某个动作完成后由JavaScript引擎执行。

As the name suggests, callback functions are anonymous or named functions that are passed as arguments to another function, or an AJAX call etc. and will be executed after a certain action is completed by the javascript engine.

例如。一旦AJAX调用返回数据,您可以传递一个要执行的回调函数。为了简单,我使用jQuery:

For eg. You can pass a callback function to be executed once an AJAX call has returned with data. Ill use jQuery for simplicity :

$.ajax( {
  url: "/my-api-path/",
  data: myParams
}).done(myCallback);

这里,myCallback是一个将在AJAX调用完成后执行的函数。在这种情况下,回调函数将使用AJAX调用返回的响应对象进行调用。注意这个回调如何作为参数传递给jQuery的AJAX API提供的.done方法。

Here, myCallback is a function that will be executed once the AJAX call completes. The callback function in this case will be called with the response object returned by the AJAX call. Notice how this callback has been passed as an argument to the .done method provided by jQuery's AJAX API.

在另一个例子中,

setTimeout( 
function() { 
alert("Im inside a callback function!"); 
}, 2000 );

这里包含警报的函数是传递给javascript中的setTimeout方法的两个参数的第一个。第二个是应该执行此函数的毫秒数。由于此函数没有名称,因此称为匿名函数。

Here the function that contains the alert is the first of the two arguments passed to the setTimeout method in javascript. The second being the amount of milliseconds after which this function should be executed. Since this function does not have a name it is called an anonymous function.

相同的代码可以重写为:

The same code could be re-written as :

var myCallback = function(){ 
   alert("Im inside a callback");
};
setTimeout(myCallback, 2000);

操作完成时立即执行回调。所以在引擎遇到setTimeout语句后,它将myCallback函数存储在引用中,然后在setTimeout语句后继续执行。一旦2秒过去,它将实现它的时间执行回调,所以执行将跳转到回调。然后警报将执行,回调函数将终止,执行将从2秒钟过去并且引擎跳转到回调时继续执行。

Callbacks are executed immediately when the action completes. So after the engine encounters the setTimeout statement it will store the myCallback function in a reference and then continue execution after the setTimeout statement. Once 2 seconds elapse, it will realise its time to execute the callback so execution will jump to the callback. Then the alert will execute, the callback function will terminate and execution will continue back from where it was when 2 seconds elapsed and the engine jumped to the callback.

希望这说明回调如何工作。

Hope this explains how callbacks work.

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

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