[英]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.isTexture
和this.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()
请注意,您不需要返回true
或false
,因为返回的表达式的计算结果类似于a == b
的布尔值,则返回布尔值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.