• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 243
  • Last Modified:

Javascript - XmlHttpRequest inside of a class

I'm trying to build a class in Javascript that has an XmlHttpRequest object as one of its members.  When you instantiate an object from this class, a new XmlHttpRequest object should be created and the request should be made.

Here is my class...

function ControlObj(ctrlName) {
     this.name = ctrlName;
     this.xhr = CreateXmlHttpRequestObject();
     this.xhr.onreadystatechange = function() {
          if (this.xhr.readyState == 4) {
               document.getElementById(ctrlName).innerHTML = this.xhr.responseText.substring(this.xhr.responseText.indexOf("~") + 1, this.xhr.responseText.indexOf("^"));
               document.getElementById(ctrlName).setAttribute('id', ctrlName + '_Loaded');
          }
     }
     this.xhr.open("GET", "HomePageAjaxControlLoader.aspx?control=" + ctrlName + "&r=" + (Math.random() * 9999999), true);
     this.xhr.send(null);
}
ControlObj.prototype.abort = function() {
     if (this.xhr != null) {
          this.xhr.abort();
     }
}

And to instantiate a new object from the class I use...

ComponentList[x] = new ControlObj(controlName);

Now according to my knowledge, this should work fine.  Yet, whenever I instantiate the object and it gets to the this.xhr.open statement, it throws an error saying that the xhr.readystate is null or not an object.  Any idea what i could be doing wrong here?
0
josephdaviskcrm
Asked:
josephdaviskcrm
1 Solution
 
MorcalavinCommented:
Your use of the 'this' keyword.  When you use an anonymous function, the 'this' keyword becomes the parent object.  So this doesn't refer to the instance of ControlObj class anymore.  Instead it should be refering to the xhr class, so you should be able to say:
if(this.readyState === 4)  ...

I've attached a relatively simple explanation of how this works.

        function Foo()
        {
            this.greetings = 'hello';
        }
        function Oof()
        {
            this.greetings = 'goodbye';
            this.foo = new Foo();
            this.foo.dothis = function()
            {
                alert(this.greetings);  //prints hello.  this refers to the calling object, ie foo
            }
        }
        var test1 = new Oof();
        test1.foo.dothis();

Open in new window

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now