Javacript class function problem

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.

I found this to be very helpful in understanding callback functions → http://recurial.com/programming/understanding-callback-functions-in-javascript/

The thing to remember is it’s an asynchronous call (The A in Ajax), so you don’t know when it’s going to come back. So you either have to manipulate the DOM somehow or use a callback function. You can have it where you don’t use Ajax asynchronously, but then you’ll be defeating its purpose in my opinion.

1 Like

Hi wa11,

you can reference ‘this’ in the same way that you reference cFunction - by assigning it to another variable outside of your onreadystatechange handler.

self is a common variable name for this purpose

var self = this;
var cFunction = this.callBackFunction;

this.request.onreadystatechange = function() {
  // you can use 'self' here to refer to your object instance
}

I just re-read your code and what you really need is access to the request object, rather than ‘this’. The same technique works:

var req = this.request;
var cFunction = this.callbackFunction;
this.request.onreadystatechange = function () {
            if (req.readyState == 4 && req.status == 200) {
                cFunction(req.responseText);
            }
        };

Hope that helps!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.