Search code examples
javascriptdom-events

JavaScript "is not a function" error when calling defined method


This is my code:

request_xml: function()
        {
        http_request = false;
                    http_request = new XMLHttpRequest();
                     if (http_request.overrideMimeType) 
                            {
                            http_request.overrideMimeType('text/xml');
                            }
                          if (!http_request)
                          {
                                return false;
                          }
                        http_request.onreadystatechange = this.response_xml;
                        http_request.open('GET', realXmlUrl, true);
                        http_request.send(null);
                        xmlDoc = http_request.responseXML;
                        
},



response_xml:function ()
    {
        if (http_request.readyState == 4)
        {
            if(http_request.status == 404 && countXmlUrl<=3)
            {
                countXmlUrl++;
                
                realXmlUrl = xmlUrl[countXmlUrl];
                this.request_xml();
            }
            if (http_request.status == 200)
            {
                xmlDoc = http_request.responseXML;
                alert("need to update3");
                this.peter_save_data();
            }
            
        }
    },

peter_save_data:function()
    {
// removed function code
},

Strangely, the alert fires without a problem but the function call underneath gives me this error:

Error: this.peter_save_data is not a function

Calling the same function from another function elsewhere works fine.


Solution

  • You could do this, right before you call the XML generation.

    var that = this;
    

    and later...

    that.peter_save_data();
    

    Because this frequently changes when changing scope by using a new function, you can't access the original value by using it. Aliasing it to that allows you still to access the original value of this.