JavaScript Callback Functions May 14th, 2013

  •  Functions are objects
    • A Function object contains a string which contains the Javascript code of the function
    • For Javascript, the distinction between code and data is sometimes blurred
    • 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)
function some_function2(url, callback) {
	var httpRequest; // create our XMLHttpRequest object
	if (window.XMLHttpRequest) {
		httpRequest = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// Internet Explorer is stupid
		httpRequest = new
			ActiveXObject("Microsoft.XMLHTTP");
 	}

	httpRequest.onreadystatechange = function() {
		// inline function to check the status
		// of our request
		// this is called on every state change
		if (httpRequest.readyState === 4 &&
				httpRequest.status === 200) {
			callback.call(httpRequest.responseXML);
			// call the callback function
		}
	};
	httpRequest.open('GET', url);
	httpRequest.send();
}
// call the function
some_function2("text.xml", function() {
	console.log(this);
});
console.log("this will run before the above callback");

Resources