开发者

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 =开发者_Python百科 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.


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


Can you assign parseXML() directly to ImageRotatorManager?

ImageRotatorManager.parseXML = function(xml, callback) { ... };

and call it like you would a static method in Java?

ImageRotatorManager.parseXML(xml, callback);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜