簡體   English   中英

用Javascript嵌套對象-匿名不是函數錯誤

[英]Nesting Objects in Javascript - Anonymous is not a function error

好的,顯然,我是Java OOP的完全新手。 我以為我理解了,但看來我只知道一小部分。 無論如何,我正在嘗試通過使用一個相當簡單的字符串來檢索數據來設置一個對象來存儲和返回XML輸入中的數據。 我想使用類似於reader.getItem().getSubItem()類的字符串來檢索數據。

下面是我嘗試的示例,但是每次嘗試調用fr.getType().isTexture() ,我都得到anonymous is not a function錯誤anonymous is not a function ,因此很明顯,我需要更改某些內容。

//Create the object by passing an XML element containing sub-elements
var fr = new FeatureReader(test.child(i));

alert(fr.getName()); //returns the object's name
alert(fr.getType().isTexture()); //"anonymous is not a function" error

function FeatureReader(feature) {
    var feat = feature;
    this.getName = function() {
        return feat.name;
    };
    this.getType = new function() {
        this.isTexture = new function() {
            if (feat.type.texture == "yes") {
                return true;
            }
            return false;
        };
        this.isModel = new function() {
            if (feat.type.model == "yes") {
                return true;
            }
            return false;
        };
    };
}

現在,顯然,我可以刪除this.isTexturethis.isModel周圍的this.isTexture this.getType = function() {}以獲取數據,但是為了學習一些知識,我想看看如何推薦它我使用與第一和第二段中提到的字符串相似的字符串來設置此對象以獲取返回值。

執行此操作時:

    this.isTexture = new function() {
        if (feat.type.texture == "yes") {
            return true;
        }
        return false;
    };

您將“ isTexture”屬性設置為構造的對象,而不是該函數。 如果從語句中刪除new關鍵字,則將“ isTexture”設置為函數。

換句話說,形式為new <some-function>的表達式對一個對象求值。

編輯 -出於相同的原因,您的“ getType”屬性將是一個對象。 但是,我認為這會起作用:

alert( fr.getType.isTexture() );

還要注意,您的if語句可以簡化:

  return feat.type.texture == "yes";

您可以做的就是簡單地分配一個對象,而不是使用new

function FeatureReader(feature) {
    var feat = feature;
    this.getName = function() {
        return feat.name;
    };
    this.getType = {
        isTexture: function() {
            return feat.type.texture == "yes";
        },
        isModel: function() {
            return feat.type.model == "yes";
        }
    };
}

然后使用如下方法:

instance.getType.isTexture()

請注意,您不需要返回truefalse ,因為返回的表達式的計算結果類似於a == b的布爾值,則返回布爾值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM