I want the AJAX callback to trigger the alert() in myFucntion with “It worked” do how can I refer to the myobject object as this in ajaxResponse?
function myobject() {
this.val = "worked";
http.onreadystatechange = function ajaxResponse() {
if (http.readyState == 4) {
this.myFunction();
}
http.send(null);
}
myobject.prototype.myFunction = function() {
alert("it "+this.val);
}
ajaxResponse is a function in parent function, it’s called closure in javascript. When a closure uses a variable which is defined in its parent function, this variable can not be destroyed from memory, while the father function finishes execution.
So, define a temporary variable like this:
Then you can use this variable objTmp in ajaxResponse.
Or you can do it like this: