p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Beginning JavaScript 5th Edition (http://p2p.wrox.com/forumdisplay.php?f=793)
-   -   Confused regarding scope and this keyword described in CH14 (http://p2p.wrox.com/showthread.php?t=99385)

canolyb1 February 21st, 2017 07:51 PM

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;
}



All times are GMT -4. The time now is 01:16 PM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.