I\'m using XMLHttpRequest, and I want to access a local variable in the success callback function.
Here is the code:
function getFileContents(filePat
In this scenario, test will be resolved as you'd expect it, but the value of this might be different. Normally, to preserve the scope, you would make it a parameter to the asynchronous function like so:
function getFileContents(filePath, callbackFn, scope) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callbackFn.call(scope, xhr.responseText);
}
}
xhr.open("GET", chrome.extension.getURL(filePath), true);
xhr.send();
}
//then to call it:
var test = "lol";
getFileContents("hello.js", function(data) {
alert(test);
}, this);