I would greatly appreciate your assistance in deciphering the JavaScript code provided in the book "Ajax in Action"

While reading through the Ajax in Action book, I came across a code snippet that has left me with a couple of questions. As someone who is new to web programming and still getting to grips with JavaScript, I am hoping for some clarity on the following:

  1. In line 37 or within the function loadXMLDoc, why does the author declare a local variable "var loader=this;" and then use it in the call "net.ContentLoader.onReadyState.call(loader);" instead of simply using "net.ContentLoader.onReadyState.call(this);"

  2. What is the reason behind the author's choice to use "net.ContentLoader.onReadyState.call(loader);" rather than "this.onReadyState();"

    /*
    url-loading object and a request queue built on top of it
    */

    /* namespacing object */
    var net=new Object();

    net.READY_STATE_UNINITIALIZED=0;
    net.READY_STATE_LOADING=1;
    net.READY_STATE_LOADED=2;
    net.READY_STATE_INTERACTIVE=3;
    net.READY_STATE_COMPLETE=4;


    /*--- content loader object for cross-browser requests ---*/
    net.ContentLoader=function(url,onload,onerror,method,params,contentType){
      this.req=null;
      this.onload=onload;
      this.onerror=(onerror) ? onerror : this.defaultError;
      this.loadXMLDoc(url,method,params,contentType);
    }

    net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
      if (!method){
        method="GET";
      }
      if (!contentType && method=="POST"){
        contentType='application/x-www-form-urlencoded';
      }
      if (window.XMLHttpRequest){
        this.req=new XMLHttpRequest();
      } else if (window.ActiveXObject){
        this.req=new ActiveXObject("Microsoft.XMLHTTP");
      }
      if (this.req){
        try{
          var loader=this;
          this.req.onreadystatechange=function(){
            net.ContentLoader.onReadyState.call(loader);
          }
          this.req.open(method,url,true);
          if (contentType){
            this.req.setRequestHeader('Content-Type', contentType);
          }
          this.req.send(params);
        }catch (err){
          this.onerror.call(this);
        }
      }
    }


    net.ContentLoader.onReadyState=function(){
      var req=this.req;
      var ready=req.readyState;
      var httpStatus=req.status;
      if (ready==net.READY_STATE_COMPLETE){
        if (httpStatus==200 || httpStatus==0){
          this.onload.call(this);
        }else{
          this.onerror.call(this);
        }
      }
    }

    net.ContentLoader.prototype.defaultError=function(){
      alert("error fetching data!"
        +"\n\nreadyState:"+this.req.readyState
        +"\nstatus: "+this.req.status
        +"\nheaders: "+this.req.getAllResponseHeaders());
    }

Answer №1

When a try/catch statement is used in ECMA-/Javascript, it generates a fresh Context. Essentially, this works similarly to an eval statement, resulting in an eval Context.

This newly created "eval Context" extends the current Scope chain, causing the Context variable this to point to the wrong context if invoked by this.onReadyState();.

By utilizing

net.ContentLoader.onReadyState.call(loader);
, the author specifically invokes the method onReadyState with the context of the loaded object (thus, referencing what this within the callee). A callee is a function (-context...) that was called by a caller (-context).


In short, ECMAscript's .call() and .apply() methods enable you to define a particular Context for a function upon invocation. This becomes essential here because try/catch initiates a new Context, leading to the incorrect value of this within the called method.


Although the above explanation holds true, the issue lies not only with the Context from try / catch, but also with the Context introduced by the anonymous function being created

this.req.onreadystatechange=function(){
    net.ContentLoader.onReadyState.call(loader);
}

Using this inside that anonymous method would once again refer to a different Context. Hence, the author stored the value of this in loader and called the method using that cached Context.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What methods can be used to restrict user input to numbers and letters only?

Is it possible to restrict the input in my text field username without using regex? I want users to only enter numbers and letters, with no white spaces or special characters. <div class="form-group has-feedback" ng-class="addUser.username.$valid ? &ap ...

How to use Javascript to pause an HTML5 video when closed

I am new to coding and currently working on a project in Adobe Edge Animate. I have managed to create a return button that allows users to close out of a video and go back to the main menu. However, I am facing an issue where the video audio continues to p ...

Null Value Returned When Making an Ajax Post Request

I'm having trouble retrieving the id of the last inserted row after posting via ajax. When I var_dump the result, the function returns HTML instead of the id data. What am I missing here? Note: The save method should return the id of the last inserte ...

Steps for sending data to a modal window

Consider this scenario: I have a function that retrieves some ids, and I utilize the following code to delete the corresponding posts: onClick={() => { Delete(idvalue[i]) }} Nevertheless, I am in need of a modal confirmation before proceeding with the ...

Inquiries regarding the vuex dynamic registration module result in a complete refresh of all Vue components

When trying to create a new Vue component, I encounter the issue of having to call store.registerModule() before creation. However, this action results in all existing Vue components being destroyed and recreated. The same issue happens when using store. ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

Tips for transforming a JSON object (originated from jquery-css-parser) into properly formatted CSS code

Currently, we are utilizing a jQuery plugin in our project to convert CSS to a JSON object. The plugin can be found at the following link: Now, we have a requirement to convert the JSON object back to CSS in string format. Unfortunately, the plugin we ar ...

Leveraging configuration files for HTML pages without any server-side code

I am currently working on developing an app using phonegap. At the moment, I have the reference to a script in every page like this: <script language="javascript" src="http://someServer/js/myscript.js"></script> If the server 'someServer ...

Sending back various results in a javascript function

I am attempting to correlate test scores with values from the level array in order to extract selected values into an output array. However, when I execute the following script in the Firebug console, I encounter the error message "TypeError: level is unde ...

Connecting a specific URL of an API to a single mobile app: A step-by-step guide

Currently, my API includes a user registration system that is utilized by a mobile application. Most of the URLs are restricted for anonymous users and require a token key for authorization, except for the register URL. The register URL needs to remain op ...

Receiving a NaN output rather than a numerical value

Experiencing what seems to be a straightforward syntax error, but I'm unable to pinpoint it. Controller: $scope.startCounter = 3; $scope.startTimeouter = function (number) { $scope.startCounter = number - 1; mytimeouter = $t ...

No data returned in AJAX response while trying to connect to a RESTful service

After creating a WCF REST service that returns a JSON response like {"Id":10,"Name":"Peter"}, I noticed that when trying to access it using the provided HTML5 code snippet, the status returned is always 0. Can anyone help me figure out what might be caus ...

What part of the system generates sessions and cookies?

Is the following statement accurate? When developing a website, I utilize frontend javascript to create cookies and backend languages such as php or ruby to manage sessions? If this is correct, does the creation of sessions involve the browser generating ...

Encountering a no-loops/no-loops eslint error in node.js code while attempting to utilize the for and for-of loops

While working on my nodejs application, I have encountered an issue with es-lint giving linting errors for using 'for' and 'for-of' loops. The error message states error loops are not allowed no-loops/no-loops. Below is the snippet of c ...

The issue of Select2 with AJAX getting hidden behind a modal is causing

I'm currently facing an issue with Select2 within a modal. The problem can be seen here: https://gyazo.com/a1f4eb91c7d6d8a3730bfb3ca610cde6 The search results are displaying behind the modal. How can I resolve this issue? I have gone through similar ...

Creating Beautiful Tabs with React Material-UI's Styling Features

I've been delving into React for a few hours now, but I'm struggling to achieve the desired outcome. My goal is to make the underline color of the Tabs white: https://i.stack.imgur.com/7m5nq.jpg And also eliminate the onClick ripple effect: ht ...

Error: JSON input abruptly ended - SyntaxError was not caught

Hey there! I've been struggling with an AJAX call that keeps throwing an error mentioned in the title. It seems like the culprit might be this line of code: var obj = jQuery.parseJSON(data);. Maybe my userData is not formatted correctly. Here's ...

avoidable constructor in a react component

When it comes to specifying initial state in a class, I've noticed different approaches being used by people. class App extends React.Component { constructor() { super(); this.state = { user: [] } } render() { return <p>Hi</p> ...

Steps for importing a json file into Chrome

Inside my file named data.json, there is a JSON object structure: { "k": : "..some object...", "a": [ "...", "bbb" ] } When working with Node.js, I can easily import this data into a variable using: let data = require("./data.json"); However, how can I ...

Exploring ways to assign a value to an HTML element utilizing Jquery in combination with ASP.NET MVC 4 complex model information

Within an ASP.NET MVC 4 view, I am utilizing data from a Model to populate various HTML elements. The model is used in the view to showcase values like: <div>@Model.Category.Name</div> etc... However, there is a specific div tag <div id="D ...