What is the callback function? I really don’t know how to use and function the js callback function before learning it. In the following article, I will introduce to you the students the example of my learning callback function. Students who need to know should not be careful not to enter the reference.
Callback function principle:
I'll leave now and I'll notify you."
This is an asynchronous process. During the process of "I'm going to" (function execution), "you" can do anything, "arrives" (function execution is completed) and "notify you" (callback) after the process of "notifying you" (callback) is carried out
example
1. Basic Methods
<script language="javascript" type="text/javascript">function doSomething(callback) {// … // Call the callbackcallback('stuff', 'goes', 'here');} function foo(a, b, c) {// I'm the callbackalert(a + " " + b + " " + c);} doSomething(foo); </script>Or use anonymous function
<script language="javascript" type="text/javascript"> function dosomething(damsg, callback){ alert(damsg); if(typeof callback == "function") callback(); } dosomething("Callback function", function(){ alert("Same as jQuery callbacks form!"); }); </script>2. Advanced Methods
Call method using javascript
<script language="javascript" type="text/javascript">function Thing(name) {this.name = name;}Thing.prototype.doSomething = function(callback) {// Call our callback, but using our own instance as the contextcallback.call(this);} function foo() {alert(this.name);} var t = new Thing('Joe');t.doSomething(foo); // Alerts "Joe" via `foo`</script>Pass parameters
<script language="javascript" type="text/javascript"> function Thing(name) {this.name = name;}Thing.prototype.doSomething = function(callback, salutation) {// Call our callback, but using our own instance as the contextcallback.call(this, salutation);} function foo(salutation) {alert(salutation + " " + this.name);} var t = new Thing('Joe');t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`</script>Pass parameters using javascript
<script language="javascript" type="text/javascript">function Thing(name) {this.name = name;}Thing.prototype.doSomething = function(callback) {// Call our callback, but using our own instance as the contextcallback.apply(this, ['Hi', 3, 2, 1]);} function foo(salutation, three, two, one) {alert(salutation + " " + this.name + " " + three + " " + two + " " + one);} var t = new Thing('Joe');t.doSomething(foo); // Alerts "Hi Joe 3 2 1" via `foo`</script>example
//If the data source provided is an integer, which is a student's score, when num<=0, it is processed by the underlying layer, and when n>0, it is processed by the upper layer.
//Copy the following function and save it to 1.js
function f(num,callback){ if(num<0) { alert("Call the low-level function to process!"); alert("Score cannot be negative, input error!"); }else if(num==0){ alert("Call the low-level function to process!"); alert("The student may not have taken the exam!"); }else{ alert("Call the high-level function to process!"); callback(); }}//Save the following test.html file in the same directory as 1.js:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><script src="1.js" type="text/javascript"></script><title>Unt titled document</title><script type="text/javascript"> function test(){ var p=document.getElementById("pp"); pp.innerText=""; var num=document.getElementById("score").value; f(num,function(){ //Anonymous high-level processing function if(num<60) alert("failed!"); else if(num<=90) alert("Excellent result!"); else alert("Excellent result!"); }) pp.innerText="by since1978 qq558064!" }</script></head><body><p>Callback function example: When the student scores <= 0 points, the bottom layer will handle it; when the score>0, the top layer will handle it. </p>Please enter student scores <input type="text" id="score"> <input type="button" onClick="test()" value=" Check out the results"><p id="pp"></p></body></html>The following are the additions from other netizens:
Callback mode in javascript:
As shown in:
function writeCode(callback){ //Execute some things, callback(); //... } function intrduceBugs(){ //....Introduce vulnerability} writeCode(intrduceBugs);We pass the application of the function to writeCode(), so that writeCode executes it at the appropriate time (return to call it later)
Let’s first look at a not-so-good example (it will be refactored later):
//Simulate the dom nodes in the search page, and return the found nodes in the array uniformly //This function is only used to find no logical processing for the dom nodes var findNodes = function(){ var i = 100000;//A large number of loops, var nodes = [];//Use to store the found dom nodes var found; while(i){ i -=1; nodes.push(found); } return nodes; } //Hide all the dom nodes found var hide = function(nodes){ var i = 0, max = nodes.length; for(;i<max;i++){ //There are brackets after findingNodes to indicate the execution immediately. First execute findNodes() and then execute hide()< hide(findNodes()); execute function} ; nodes[i].style.display="none"} The above method is inefficient. It is thought that hide() must traverse the array nodes returned by findNodes() again. How to avoid such unnecessary loops. We cannot directly hide the query node in findNodes (this search can modify the logical coupling), so it is no longer a general function. The solution is to use callback mode, where you can pass the hidden logic of the node to findNodes() in a callback function and delegate it to execute //Refactor findNodes to accept a callback function var findNodes = fucntion(callback){ var i = 100000, nodes = [], found; //Check whether the callback function is available for callback if(typeof callback !== 'function'){ callback = false; } while(i){ i -= 1; if(callback){ callback(found); } nodes.push(found); } return nodes; } //Checkback function var hide = function(node){ node.style.display = 'none '; } //Find the subsequent node and hide it in subsequent execution findNodes(hide);//Execute findNodes first and then hide. Of course, the callback function can also be created when calling the main function: findNodes(function(node){node.style.display = 'none';});