好吧,显然我是 Javascript 中 OOP 的新手。我以为我明白了,但看来我只知道一小部分。无论如何,我想要做的是设置一个对象,通过使用相当简单的字符串来检索数据,来存储和返回 XML 输入中的数据。我想使用类似于 reader.getItem().getSubItem()
或类似内容的字符串检索数据。
下面是我尝试的示例,但每次尝试调用 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.isTexture
和 this.isModel
周围的 this.getType = function() {}
> 获取我的数据,但为了学习一些东西,我想看看如何建议我设置此对象以使用类似于我在第一段和第二段中提到的字符串来获取返回值。
最佳答案
当你这样做时:
this.isTexture = new function() {
if (feat.type.texture == "yes") {
return true;
}
return false;
};
您将“isTexture”属性设置为构造的对象,而不是该函数。如果您删除 new
语句中的关键字,您将把“isTexture”设置为一个函数。
new <some-function>
形式的表达式换句话说,计算结果为一个对象。
edit — 出于同样的原因,您的“getType”属性也将成为一个对象。不过,我认为这会起作用:
alert( fr.getType.isTexture() );
另请注意,您的 if
语句可以简化:
return feat.type.texture == "yes";
关于javascript - 在 Javascript 中嵌套对象 - 匿名不是函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23067906/