2014-04-14 39 views
0

好吧,所以我是一個完全新手到JavaScript的面向對象,顯然。我以爲我明白了,但看來我只知道一小部分。無論如何,我想要做的是設置一個對象來存儲和返回XML輸入的數據,通過使用相當簡單的字符串來檢索數據。我想用類似於reader.getItem().getSubItem()或類似的字符串檢索數據。在Javascript中嵌套對象 - 匿名不是一個函數錯誤

下面是我嘗試的一個例子,但每次我嘗試撥打電話fr.getType().isTexture()時都會收到錯誤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.getType = function() {}得到我的數據,但對於學習的東西的緣故,我想看看它是如何建議我設置對象直到使用類似於第一段和第二段中提到的字符串來獲取返回的值。

+0

這應該有助於http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – elclanrs

回答

0

你可以做的是簡單地分配對象,而不是使用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 返回布爾值。

+0

啊,起初沒有聽到==。做得非常好,完美地回答了我的問題,並且代碼少於預期!非常感謝你! – DGolberg

+0

你會想要在內部對象聲明中刪除那些分號 –

+0

是的,我使用Eclipse來編寫初始代碼,它指出了一個對我來說。這實際上是在Photoshop中使用,但考慮ESTK的不穩定性,我已經開始在Eclipse中編寫我的代碼,然後在ESTK中進行調試。感謝您指出這一點,但其他人可能錯過了它。 – DGolberg

2

當你這樣做:

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"; 
+0

好吧,但現在我得到'未定義不是一個對象'當試圖訪問' isTexture()' – DGolberg

+0

@DGolberg啊好吧「getType」也會*成爲一個對象;我錯過了警報調用中的函數調用。 – Pointy

+0

@Dololberg我認爲你有點複雜,但爲什麼不簡單地分配一個對象呢?請參閱https://gist.github.com/elclanrs/8ef4012a4ea3f5b7213e – elclanrs