In JavaScript, I know that a closure is can be defined as a nested function that has access to its containing function’s variables. For example:
function outerFunction(x, y) { function innerFunction() { return x + y + 10; } return innerFunction; }
Now, the following code is wiring up a callback for the onreadystatechange property of the request object; however, I was wondering if, by definition, this is also considered to be a closure:
/* This is a contrived example, I know. * Bear with me - it demonstrates the point I'm trying to convey. */ function submitHandler() { var oRequest = createRequest(); // assume I'm getting an instance of the xhr var sUsername = 'Tom'; // assume this is needed for work in the handler var This = this; oRequest.onreadystatechange = function() { This.handleResponse(oRequest, sUsername) } } function handleResponse(oResponse, sUsername) { if(oResponse.readyState === 4 && oResponse.status === 200) { // do work with the username } else { // we're not done yet... } }
I realize that the handleResponse function could also just be written as an anonymous function in the context of submitHandler, but I find that more complex Ajax code can be more readable and easily maintained if callbacks are defined outside the scope of the function calling back to them. Again, this is a contrived example that I’m using in hopes of simply demonstrating the point of my question.
Yes, you are correct in assuming that it is a closure by definition.
It sounds like you know your stuff but here is a good, extensive article on javascript closures.