How to access method variables from within an anonymous function in JavaScript?

Posted by Hussain on Stack Overflow See other posts from Stack Overflow or by Hussain
Published on 2010-05-23T21:54:00Z Indexed on 2010/05/23 22:10 UTC
Read the original article Hit count: 312

Filed under:
|

I'm writing a small ajax class for personal use. In the class, I have a "post" method for sending post requests. The post method has a callback parameter. In the onreadystatechange propperty, I need to call the callback method.

Something like this:

this.requestObject.onreadystatechange = function() {
    callback(this.responseText); 
}

However, I can't access the callback variable from within the anonomous function. How can I bring the callback variable into the scope of the onreadystatechange anonomous function?

edit:

Here's the full code so far:

function request()
{
this.initialize = function(errorHandeler)
{
try {
try {
this.requestObject = new XDomainRequest();
} catch(e) {
try {
this.requestObject = new XMLHttpRequest();
} catch (e) {
try {
this.requestObject = new ActiveXObject("Msxml2.XMLHTTP"); //newer versions of IE5+
} catch (e) {
this.requestObject = new ActiveXObject("Microsoft.XMLHTTP"); //older versions of IE5+
}
}
} 
} catch(e) {
errorHandeler();
}
}

this.post = function(url,data) { var response;var escapedData = ""; if (typeof data == 'object') { for (i in data) { escapedData += escape(i)+'='+escape(data[i])+'&'; } escapedData = escapedData.substr(0,escapedData.length-1); } else { escapedData = escape(data); } this.requestObject.open('post',url,true); this.requestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); this.requestObject.setRequestHeader("Content-length", data.length); this.requestObject.setRequestHeader("Connection", "close"); this.requestObject.onreadystatechange = function() { if (this.readyState == 4) { // call callback function } } this.requestObject.send(data); }

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about scope