function()存在但原型function()不存在。为什么?

时间:2011-07-02 20:54:16

标签: javascript function prototype-programming

我正在创建一个名为ImageRotatorManager的JavaScript类来管理动态加载的幻灯片。通过xml加载图像时,我定义了以下函数:

/* 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
};

成功调用函数parseXML(xml, callback)

但是,如果我将parseXML()定义为ImageRotatorManager.prototype.parseXML = function (xml, callback)并使用ImageRotatorManager.parseXML(xml, callback);调用此函数,则会收到以下错误:

  

ImageRotatorManager.parseXML不是函数

为什么会出现此错误?我使用这个签名进行其他函数调用,它们工作正常。

2 个答案:

答案 0 :(得分:1)

您无法以这种方式致电.parseXML()

您已将其添加到原型中,因此您必须在该类的实例上调用它,而不是使用类名本身。

试试这个:

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

答案 1 :(得分:1)

您可以直接将parseXML()分配给ImageRotatorManager吗?

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

并像在Java中使用静态方法一样调用它?

ImageRotatorManager.parseXML(xml, callback);