The value of 'this' in the callback function

I have this code to execute ajax request in webservice:

var MyCode = {
    req: new XMLHttpRequest(), // firefox only at the moment

    service_url: "http://url/to/Service.asmx",

    sayhello: function() {
        if (this.req.readyState == 4 || this.req.readyState == 0) {
            this.req.open("POST", this.service_url + '/HelloWorld', true);
            this.req.setRequestHeader('Content-Type','application/json; charset=utf-8');
            this.req.onreadystatechange = this.handleReceive; 
            var param = '{}';
            this.req.send(param);
        }
    },

    handleReceive: function() {
        if (this.req.readyState == 4) {
            // todo: using eval for json is dangerous
            var response = eval("(" + this.req.responseText + ")");
            alert(response);
        }
    }
}

It is called using MyCode.sayhello (), of course.

The problem is that "req is not defined" in the first line of the handleReceive function. It receives the call 4 times, so I know that the code above sends a request to the server.

How can i solve this?

+3
source share
4 answers

The classic closure problem. When you receive a callback, the closure actually refers to the HTTP object already.

You can do the following: someone suggests:

var that = this;
this.req.onreadystatechange = function() { this.handleReceive.apply(that, []); };

OR just follow these steps:

var that = this;
this.req.onreadystatechange = function() { that.handleReceive(); };
+4
source

, , MyCode.

var MyCode = {
    req: new XMLHttpRequest(), // firefox only at the moment

    self = this

    ...
}

"" .

+2

Change this:

this.req.onreadystatechange = this.handleReceive;

:

var self = this;
this.req.onreadystatechange = function() { self.handleReceive(); }

This creates a closure that should fix your problems.

0
source

you can make it work by changing

this.req.onreadystatechange = this.handleReceive;

to

var that = this;
this.req.onreadystatechange = function() { this.handleReceive.apply(that, []); };

The .prototype.apply function can be used to call the function, and explicitly the thisfunction arguments.

0
source

Source: https://habr.com/ru/post/1707938/


All Articles