Note that there are some explanatory texts on larger screens.

plurals
  1. POBased on how they are constructed, can callbacks also be defined as closures?
    primarykey
    data
    text
    <p>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:</p> <pre><code>function outerFunction(x, y) { function innerFunction() { return x + y + 10; } return innerFunction; } </code></pre> <p>Now, the following code is wiring up a callback for the <code>onreadystatechange</code> property of the request object; however, <strong>I was wondering if, by definition, this is also considered to be a closure</strong>:</p> <pre><code>/* 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 &amp;&amp; oResponse.status === 200) { // do work with the username } else { // we're not done yet... } } </code></pre> <p>I realize that the <code>handleResponse</code> function could also just be written as an anonymous function in the context of <code>submitHandler</code>, 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload