【问题标题】:function() exists but prototype function() doesn't exist. Why?function() 存在,但原型 function() 不存在。为什么?
【发布时间】:2011-07-02 20:54:16
【问题描述】:

我正在创建一个名为 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 不是函数

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

【问题讨论】:

    标签: javascript function prototype-programming


    【解决方案1】:

    你不能那样打电话给.parseXML()

    您已将它添加到 prototype,因此您必须在类的 instance 上调用它,而不是使用类名本身。

    试试这个:

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

    【讨论】:

    • 我也试过打电话给this.parseXML(),但这也不能解决我的问题。有什么想法吗?
    • @Kyle:小心this。它指的是什么取决于上下文。
    • @Kyle 请参阅更新 - .get() 回调中的 this 将发生变化。
    • 太棒了!你是绝对正确的,this 在匿名函数中发生了变化。谢谢 -
    • @Kyle 不客气。 FWIW,this 每个函数调用都会发生变化。
    【解决方案2】:

    你能把parseXML()直接分配给ImageRotatorManager吗?

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

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

    ImageRotatorManager.parseXML(xml, callback);
    

    【讨论】:

    • 这可以工作,但这里真正的问题是如何在同一类的 prototyped 方法之间调用。
    • 嗨,大卫,感谢您的建议。我更喜欢上面的答案,仅仅是因为它消除了对静态函数的需求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2020-03-21
    • 1970-01-01
    相关资源
    最近更新 更多