Search code examples
javascriptfunctionprototype-programming

function() exists but prototype function() doesn't exist. Why?


I am creating a JavaScript class called ImageRotatorManager to manage a dynamically-loaded slideshow. When loading the images via xml, I have the following functions defined:

/* Loads configuration settings for the image rotator */
ImageRotatorManager.prototype.loadXML = function (callback) {
    jQuery.get("assets/image-rotator.xml", {}, function (xml) {
            parseXML(xml, callback); //the callback function                                             
    });
};

/* Loads configuration settings for the image rotator */
function parseXML(xml, callback) {
    //find every image and add the image to the '#slideshow' div
};

the function parseXML(xml, callback) is called successfully.

However if I define parseXML() as ImageRotatorManager.prototype.parseXML = function (xml, callback) and call this function using ImageRotatorManager.parseXML(xml, callback);, I receive the following error:

ImageRotatorManager.parseXML is not a function

Why do I get this error? I make other function calls using this signature and they work fine.


Solution

  • You can't call .parseXML() that way.

    You've added it to the prototype so you must call it on an instance of the class, not using the class name itself.

    Try this:

    ImageRotatorManager.prototype.loadXML = function (callback) {
        var self = this;
        jQuery.get("assets/image-rotator.xml", {}, function (xml) {
            self.parseXML(xml, callback); //the callback function
        });
    };