Hi, I have created small JavaScript ajax function to simulate class behavior. Following is my code:
var Ajax = new function (param, callBackFunction) {
this.param = param;
this.request = new XMLHttpRequest();
this.callBackFunction = callBackFunction;
this.init = function () {
this.request.open('POST', this.param.url, true);
if (this.param.method == 'POST' || this.param.method == 'post') {
this.request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
var cFunction = this.callBackFunction;
this.request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cFunction(this.responseText);
}
};
this.request.send(this.param.data);
};
};
Ajax.param = {
value: 'value=myvalue',
url: 'http://myurl.com',
method: 'post'
};
Ajax.callBackFunction = function (response) {
console.log(response);
};
Ajax.init();
This works well. What I want to know is using var cFunction = this.callBackFunction
is not the proper way of calling the function inside the onreadystatechange
function. But as we know we cannot use this
inside onreadystatechange
function. How do I inherit my class (Ajax
) properties inside onreadystatechange
function with this
? Help is appreciated. Thank you.