How to structure javascript callback so that function scope is maintained properly

Posted by Chetan on Stack Overflow See other posts from Stack Overflow or by Chetan
Published on 2010-05-24T22:44:13Z Indexed on 2010/05/24 22:51 UTC
Read the original article Hit count: 330

I'm using XMLHttpRequest, and I want to access a local variable in the success callback function.

Here is the code:

function getFileContents(filePath, callbackFn) {  
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            callbackFn(xhr.responseText);
        }
    }
    xhr.open("GET", chrome.extension.getURL(filePath), true);
    xhr.send();
}

And I want to call it like this:

var test = "lol";

getFileContents("hello.js", function(data) {
    alert(test);
});

Here, test would be out of the scope of the callback function, since only the enclosing function's variables are accessible inside the callback function. What is the best way to pass test to the callback function so the alert(test); will display test correctly?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about function