I am trying to make an XMLHttpRequest to a server using JavaScript. In the handler function, I need to call a method from the surrounding class. Is there a way to achieve this?
Understanding how this
works in JavaScript can be confusing. I have experimented with different permutations of using this
and bind(this)
, but so far, my attempts have been unsuccessful.
class ServerRequest
{
askServer(url)
{
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Got the response
this.foo().bind(this); // How do I access the foo method??
}
}
request.open('GET', url);
request.send();
}
foo()
{
// Perform some action here
}
}
All I want is to be able to call the foo method, but when I try, Firefox Console displays the message "TypeError: this.foo is not a function".