在Javascript中嵌套对象 - 匿名不是函数错误

时间:2014-04-14 18:49:47

标签: javascript oop nested

好的,显然我是Javascript中OOP的完全新手。我以为我明白了,但似乎我只知道一小部分。无论如何,我要做的是设置一个对象来存储和返回XML输入中的数据,方法是使用一个相当简单的字符串来检索数据。我想用类似reader.getItem().getSubItem()之类的字符串检索数据。

以下是我尝试的示例,但每次尝试拨打anonymous is not a function时都会收到错误fr.getType().isTexture(),所以很明显,我需要更改内容。

//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.getType = function() {}this.isTexture周围的this.isModel来获取我的数据,但为了学习一些东西,我想看看如何我建议我设置这个对象,使用类似于我在第一和第二段中提到的字符串来获取返回的值。

2 个答案:

答案 0 :(得分: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";

答案 1 :(得分: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布尔值  返回一个布尔值。