Home > Article > Web Front-end > What is a callback function in jquery
In jquery, the callback function is a function that is passed as a parameter. Function A is passed as a parameter (function reference) to another function B, and this function B executes function A, then function A is called a callback function; if there is no name (function expression), it is called an anonymous callback function. The use of callback functions can greatly improve the efficiency of programming, which makes it widely used in modern programming.
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
Functions are also objects
If you want to understand the callback function, you must first clearly understand the rules of the function . In JavaScript, functions are weird, but they are indeed objects. To be precise, a function is a Function object created using the Function() constructor. The Function object contains a string that contains the JavaScript code of the function. If you are coming from C or Java, this may seem strange. How can the code be a string? But with javascript, this is commonplace. The distinction between data and code is blurry.
//可以这样创建函数 var fn = new Function("arg1", "arg2", "return arg1 * arg2;"); fn(2, 3); //6
One advantage of doing this is that you can pass code to other functions, or you can pass regular variables or objects (because the code is literally just an object).
Passing functions as callbacks
It’s easy to pass a function as a parameter.
function fn(arg1, arg2, callback){ var num = Math.ceil(Math.random() * (arg1 - arg2) + arg2); callback(num); //传递结果 } fn(10, 20, function(num){ console.log("Callback called! Num: " + num); }); //结果为10和20之间的随机数
Maybe this seems cumbersome, or even a bit stupid, why not return the results normally? But when you have to use a callback function, you may not think so!
Traditional functions input data in the form of parameters and use return statements to return values. Theoretically, there is a return statement at the end of the function, which is structurally: an input point and an output point. This is easier to understand. A function is essentially a mapping of the implementation process between input and output.
However, when the function implementation process is very long, do you choose to wait for the function to complete processing, or use a callback function for asynchronous processing? In this case, it becomes crucial to use callback functions, for example: AJAX requests. If you use a callback function for processing, the code can continue to perform other tasks without waiting in vain. In actual development, asynchronous calls are often used in JavaScript, and it is even highly recommended here!
Below is a more comprehensive example of using AJAX to load an XML file, and uses the call() function to call the callback function in the context of the requested object.
function fn(url, callback){ var httpRequest; //创建XHR httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() : //针对IE进行功能性检测 window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : undefined; httpRequest.onreadystatechange = function(){ if(httpRequest.readystate === 4 && httpRequest.status === 200){ //状态判断 callback.call(httpRequest.responseXML); } }; httpRequest.open("GET", url); httpRequest.send(); } fn("text.xml", function(){ //调用函数 console.log(this); //此语句后输出 }); console.log("this will run before the above callback."); //此语句先输出
We request asynchronous processing, which means that when we start the request, we tell them to call our function when they are completed. In actual situations, the onreadystatechange event handler must also consider the situation of request failure. Here we assume that the xml file exists and can be successfully loaded by the browser. In this example, the asynchronous function is assigned to the onreadystatechange event and therefore will not be executed immediately.
Ultimately, the second console.log statement is executed first because the callback function is not executed until the request is completed.
The above example is not easy to understand, so take a look at the following example:
function foo(){ var a = 10; return function(){ a *= 2; return a; }; } var f = foo(); f(); //return 20. f(); //return 40.
函数在外部调用,依然可以访问变量a。这都是因为javascript中的作用域是词法性的。函数式运行在定义它们的作用域中(上述例子中的foo内部的作用域),而不是运行此函数的作用域中。只要f被定义在foo中,它就可以访问foo中定义的所有的变量,即便是foo的执行已经结束。因为它的作用域会被保存下来,但也只有返回的那个函数才可以访问这个保存下来的作用域。返回一个内嵌匿名函数是创建闭包最常用的手段。
回调是什么?
看维基的 Callback_(computer_programming) 条目:
In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.
jQuery文档How jQuery Works#Callback_and_Functio...条目:
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes. Another important thing to know is how to properly pass the callback. This is where I have often forgotten the proper syntax.
百科:回调函数
回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用为调用它所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
因此,回调本质上是一种设计模式,并且jQuery(包括其他框架)的设计原则遵循了这个模式。
在JavaScript中,回调函数具体的定义为:函数A作为参数(函数引用)传递到另一个函数B中,并且这个函数B执行函数A。我们就说函数A叫做回调函数。如果没有名称(函数表达式),就叫做匿名回调函数。
因此callback 不一定用于异步,一般同步(阻塞)的场景下也经常用到回调,比如要求执行某些操作后执行回调函数。
例子
一个同步(阻塞)中使用回调的例子,目的是在func1代码执行完成后执行func2。
var func1=function(callback){ //do something. (callback && typeof(callback) === "function") && callback(); } func1(func2); var func2=function(){ }
异步回调的例子:
$(document).ready(callback); $.ajax({ url: "test.html", context: document.body }).done(function() { $(this).addClass("done"); }).fail(function() { alert("error"); }).always(function() { alert("complete"); }); /** 注意的是,ajax请求确实是异步的,不过这请求是由浏览器新开一个线程请求,当请求的状态变更时,如果先前已设置回调,这异步线程就产生状态变更事件放到 JavaScript引擎的处理队列中等待处理。*/
回调什么时候执行
回调函数,一般在同步情境下是最后执行的,而在异步情境下有可能不执行,因为事件没有被触发或者条件不满足。
为什么会需要回调函数
把一个函数作为参数传入到我们的主函数中,让这个函数按照我们的想法顺序进行执行。
我们希望能够在弹出提示信息之后,在我们进行点击确定之后,再执行一个函数内容,这个时候就会用到回调。
因为在程序是非堵塞的,弹出消息之后,在我们还没在弹出框里面进行点击确认或者选择的时候,程序已经执行下面的语句了;
这样我们就没有选择权了,不符合用户习惯,所以我们采用回调函数的方式;
采用了回调函数之后,我们就把callback与主函数体合二为一了,就会是顺序执行了,就可以进行选择和点击确认了。
分开写会导致不能对弹出框进行确认
回调函数作为参数加入到主函数中,可以使得回调在主函数中进行顺序执行,弹出框也就可以正常了。
回调函数的使用场合
资源加载:动态加载js文件后执行回调,加载iframe后执行回调,ajax操作回调,图片加载完成执行回调,AJAX等等。
DOM事件及Node.js事件基于回调机制(Node.js回调可能会出现多层回调嵌套的问题)。
setTimeout的延迟时间为0,这个hack经常被用到,settimeout调用的函数其实就是一个callback的体现
链式调用:链式调用的时候,在赋值器(setter)方法中(或者本身没有返回值的方法中)很容易实现链式调用,而取值器(getter)相对来说不好实现链式调用,因为你需要取值器返回你需要的数据而不是this指针,如果要实现链式方法,可以用回调函数来实现setTimeout、setInterval的函数调用得到其返回值。由于两个函数都是异步的,即:他们的调用时序和程序的主流程是相对独立的,所以没有办法在主体里面等待它们的返回值,它们被打开的时候程序也不会停下来等待,否则也就失去了setTimeout及setInterval的意义了,所以用return已经没有意义,只能使用callback。callback的意义在于将timer执行的结果通知给代理函数进行及时处理。
回调函数的传递
上面说了,要将函数引用或者函数表达式作为参数传递。
$.get('myhtmlpage.html', myCallBack);//这是对的 $.get('myhtmlpage.html', myCallBack('foo', 'bar'));//这是错的,那么要带参数呢? $.get('myhtmlpage.html', function(){//带参数的使用函数表达式 myCallBack('foo', 'bar'); });
另外,最好保证回调存在且必须是函数引用或者函数表达式:(callback && typeof(callback) === "function") && callback();
回调函数的使用示例
例子1
如果不用回调,在alert弹出框之后,我们还没有点击确认的时候,就刷新了,不合常规。
例子2
如果不用回调,ajax与弹出框函数分开写,结果就会是在弹出框之后,我们还没进行点击选择,就已经发送ajax了,然后再弹出弹出框,不符合我们的需求,所以不能这样。
function ops(act,uid) { callback = { "ok":function(){ $.ajax({ url:common_ops.buildWebUrl("/account/ops"), type:'POST', data:{ act:act, uid:uid, }, dataType:'json', success:function(res){ allback = null; if(res.code == 200) { callback =function () { window.location.reload(); } } common_ops.alert(res.msg,callback); } }); }, "cancel":function(){ } }; //记住callback是一个回调函数 //回调函数是作为一个参数在函数中 //然后在函数内部让他运行 common_ops.confirm((act == "remove")?"确定删除吗?":"确定恢复吗?",callback); //四个参数 //第一个是信息 //第二个是按钮 //第三个是成功的方法 //第四个是失败的方法 confirm:function( msg,callback ){ callback = ( callback != undefined )?callback: { 'ok':null, 'cancel':null }; layer.confirm( msg , { btn: ['确定','取消'] }, function( index ){ if( typeof callback.ok == "function" ){ callback.ok(); layer.close( index ); } }, function( index ){ if( typeof callback.cancel == "function" ){ callback.cancel(); layer.close( index ); } }); },
例子3
<!DOCTYPE html> <html> <head> </head> <body> <div> <button>按钮</button> </div> </body> </html> <script src="./jquery-3.6.1.min.js"></script> <!-- 不用回调的 --> <!-- <script type="text/javascript"> var object = { init:function(){ this.eventbind(); }, eventbind:function(){ $("button").click(function(){ alert("111"); }) // 不用回调这边都看不到弹出框,更不要说点击确定了 window.location.reload(); } } $(document).ready(function(){ object.init(); }) </script> --> <!-- 用回调的 --> <script type="text/javascript"> var back = "回调函数" function callback(){ alert(back); window.location.reload(); } var object = { main:"主函数", tanchu:function(msg,callback){ alert(object.main); if (typeof callback == "function"){ callback(); } }, } $(document).ready(function(){ $("button").click(function(){ object.tanchu("信息",callback); }) }) </script>
代码4代码优化
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <div> <button id="noback">按钮</button> <hr> <button id="hasbac">按钮</button> </div> </body> </html> <script src="./jquery-3.6.1.min.js"></script> <!-- 不用回调的 --> <!-- <script type="text/javascript"> var obje = { init:function(){ this.eventbind(); }, eventbind:function(){ $("#noback").click(function(){ alert("1"); }) // 还没出现111呢 已经弹出1了 alert("2 没有弹出1 应该先弹出1的"); } } $(document).ready(function(){ obje.init(); }) </script> --> <!-- 用回调的 --> <script type="text/javascript"> var hasbac = { main:"主函数", back:"回调函数", init:function(){ this.eventbind(); }, eventbind:function(){ // 把callback让入了tanchu方法中,就会顺序执行了 // 如果直接写会导致直接弹出 $("#hasbac").click(function(){ hasbac.tanchu("点击",hasbac.callback); }) // alert(hasbac.back); // window.location.reload(); }, // 以下两个就是回调函数的写法 tanchu:function(msg,func){ alert(msg); alert(hasbac.main); if (typeof hasbac.callback == "function"){ hasbac.callback(); } }, callback:function(){ alert(hasbac.back); window.location.reload(); }, } $(document).ready(function(){ hasbac.init(); }) </script>
总结总述
函数作为参数输入到函数中,在主函数中进行顺序执行,就是回调函数。
【推荐学习:jQuery视频教程、web前端视频】
The above is the detailed content of What is a callback function in jquery. For more information, please follow other related articles on the PHP Chinese website!