回调机制.
回调机制:
window中:
例如按钮的点击事件,对于控制台等程序,一般程序从Main开始.
例如当发生按钮的点击事件的时候,是操作系统去调用执行对应的方法,而非人为用代码调用.即是使用回调的机制.
js中:
Functions are objects
Functions in Javascript are actually objects. Specifically, they’re Function
objects created with the Function
constructor. A Function
object contains a string which contains the Javascript code of the function.
1 // you can create a function by passing the 2 // Function constructor a string of code 3 var func_multiply = new Function("arg1", "arg2", "return arg1 * arg2;"); 4 func_multiply(5,10); // => 50
One benefit of this function-as-object concept is that you can pass code to another function in the same way you would pass a regular variable or object (because the code is literally just an object).
Passing a function as a callback
1 // define our function with the callback argument 2 function some_function(arg1, arg2, callback) { 3 // this generates a random number between 4 // arg1 and arg2 5 var my_number = Math.ceil(Math.random() * 6 (arg1 - arg2) + arg2); 7 // then we're done, so we'll call the callback and 8 // pass our result 9 callback(my_number); 10 } 11 // call the function 12 some_function(5, 15, function(num) { 13 // this anonymous function will run when the 14 // callback is called 15 console.log("callback called! " + num); 16 });
It might seem silly to go through all that trouble when the value could just be returned normally, but there are situations where that’s impractical and callbacks are necessary.
Don’t block the way
Traditionally functions work by taking input in the form of arguments and returning a value using a return statement (ideally a single return statement at the end of the function: one entry point and one exit point). This makes sense. Functions are essentially mappings between input and output.
Javascript gives us an option to do things a bit differently. Rather than wait around for a function to finish by returning a value, we can use callbacks to do it asynchronously. This is useful for things that take a while to finish, like making an AJAX request, because we aren’t holding up the browser. We can keep on doing other things while waiting for the callback to be called. In fact, very often we are required (or, rather, strongly encouraged) to do things asynchronously in Javascript.
Here’s a more comprehensive example that uses AJAX to load an XML file, and uses the call() function to call a callback function in the context of the requested object (meaning that when we call the this
keyword inside the callback function it will refer to the requested object):
1 function some_function2(url, callback) { 2 var httpRequest; // create our XMLHttpRequest object 3 if (window.XMLHttpRequest) { 4 httpRequest = new XMLHttpRequest(); 5 } else if (window.ActiveXObject) { 6 // Internet Explorer is stupid 7 httpRequest = new 8 ActiveXObject("Microsoft.XMLHTTP"); 9 } 10 11 httpRequest.onreadystatechange = function() { 12 // inline function to check the status 13 // of our request 14 // this is called on every state change 15 if (httpRequest.readyState === 4 && 16 httpRequest.status === 200) { 17 callback.call(httpRequest.responseXML); 18 // call the callback function 19 } 20 }; 21 httpRequest.open('GET', url); 22 httpRequest.send(); 23 } 24 // call the function 25 some_function2("text.xml", function() { 26 console.log(this); 27 }); 28 console.log("this will run before the above callback");
In this example we create the httpRequest
object and load an XML file. The typical paradigm of returning a value at the bottom of the function no longer works here. Our request is handled asynchronously, meaning that we start the request and tell it to call our function when it finishes.
We’re using two anonymous functions here. It’s important to remember that we could just as easily be using named functions, but for sake of brevity they’re just written inline. The first anonymous function is run every time there’s a state change in our httpRequest
object. We ignore it until the state is 4 (meaning it’s done) and the status is 200 (meaning it was successful). In the real world you’d want to check if the request failed, but we’re assuming the file exists and can be loaded by the browser. This anonymous function is assigned to httpRequest.onreadystatechange
, so it is not run right away but rather called every time there’s a state change in our request.
When we finally finish our AJAX request, we not only run the callback function but we use the call()
function. This is a different way of calling a callback function. The method we used before of just running the function would work fine here, but I thought it would be worth demonstrating the use of the call()
function. Alternatively you could use the apply()
function (the difference between the two is beyond the scope of this tutorial, but it involves how you pass arguments to the function).
The neat thing about using call()
is that we set the context in which the function is executed. This means that when we use the this
keyword inside our callback function it refers to whatever we passed as the first argument for call()
. In this case, when we refer to this inside our anonymous callback function we are referring to the responseXML
from the AJAX request.
Finally, the second console.log statement will run before the first, because the callback isn’t executed until the request is over, and until that happens the rest of the code goes right on ahead and keeps running.