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?
josephdaviskcrmAsked:
Who is Participating?
 
MorcalavinConnect With a Mentor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.