We help IT Professionals succeed at work.

Javascript - XmlHttpRequest inside of a class

Medium Priority
Last Modified: 2012-05-06
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);
ControlObj.prototype.abort = function() {
     if (this.xhr != null) {

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?
Watch Question

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();

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.