View Single Post
  #1 (permalink)  
Old February 21st, 2017, 07:51 PM
canolyb1 canolyb1 is offline
Registered User
Points: 8, Level: 1
Points: 8, Level: 1 Points: 8, Level: 1 Points: 8, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Feb 2017
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default Confused regarding scope and this keyword described in CH14

In chapter 14 while writing the HTTP Request Constructor the book mentions that in order to get around scope it's using tempRequest as a pointer to point to the specific object.

I'm still relatively new to Javascript and I'm trying to get a grasp on scope and how the this keyword works. From everything I read, in this case it does not make sense to do this. So I tested and changed the inside condition to this.readystate instead of the tempRequest and added a console.log to verify. The function works just the same and the object that is referenced by this is the XMLHttpRequest object.

I can see where this would needed especially if you're calling functions that are called by other objects but in this case the reqReadyStateChange() function is still called by the XMLHttpRequest object.

The book makes this further confusing by saying "...because this points to the reqReadystatechange() function indeed of the HttpRequest object."

From what I gather this property will never be set to a function. It will be set to the object that is making the call.

Please tell me I'm not losing my mind...

From Book:
HTML Code:
function HttpRequest(url, callback) {
    this.request = new XMLHttpRequest();
    this.request.open("GET", url);

    var tempRequest = this.request; // <---- I DONT SEE THE NEED FOR THIS
    
    function reqReadyStateChange() {
        if (tempRequest.readyState == 4) {
            if (tempRequest.status == 200) {
                callback(tempRequest.responseText);
            } else {
                alert("An error occurred trying to contact the server.");
            }
        }
    }
    
    this.request.onreadystatechange = reqReadyStateChange;
}

HttpRequest.prototype.send = function () {
    this.request.send(null);
};
Tested by me: (works exactly the same)
The added console.log shows that the same object is set as this when the function is called.
HTML Code:
	function reqReadyStateChange() {
		console.log(this); // <-- THIS POINTS TO THE XMLHTTPREQUEST OBJECT
		if (this.readyState == 4) {
			if (this.status == 200) {
				callback(this.responseText);
			} else {
				alert("An error occurred trying to contact the server.");
			}
		}
	}

	this.request.onreadystatechange = reqReadyStateChange;
}
Reply With Quote