0

我有两个对象

function Response(dbResponseId, responseText){
    this.response = {
        "dbResponseId" : dbResponseId,
        "responseText" : responseText,
        "isDeleted" : false,

    };  

    this.setResponseText = function(responseText){
        this.response.responseText = responseText;
        return this.response;

    };

    this.getId = function(){
        return this.response.frontEndId;
    };
    this.deleted = function(){
        this.response.isDeleted = true;
    };
    return this.response; 
}

function OptionGroup(responses, dbOptionGroupId,isDeleted,id){
    this.optionGroup = {"dbOptionGroupId" : dbOptionGroupId, "responses" : responses, "isDeleted" : isDeleted,"frontEndId" : id};

    this.setResponses = function(responses){
        this.optionGroup.responses = responses;
        return this.optionGroup;
    };
    this.addResponse = function(response){
        this.optionGroup.responses.push(response);
        return this.optionGroup;
    };
    this.getId = function(){
        return this.optionGroup.frontEndId;
    };
    this.setId = function(id){
        this.optionGroup.frontEndId = id;
        return this.optionGroup;
    };
    this.deleted = function(){
        this.optionGroup.isDeleted = true;
        return this.optionGroup;
    };
    this.getResponsesById = function(id){
        for(var i = 0; i < this.optionGroup.responses.length;i++){
            if(id == this.optionGroup.responses[i].getId()){
                return this.optionGroup.responses[i];
            }
        }
        return null;
    };

    return this.optionGroup;
}

但是,当我尝试调用我创建的任何函数时,控制台会告诉我该对象没有这样的函数。当我在控制台中打印出 Response 或 OptionGroup 对象时,我可以看到对象中的字段,但看不到任何功能。

到底是怎么回事?

4

2 回答 2

2

当您从用作构造函数的对象返回某些内容时,如上面的代码所做的那样,该值就是new调用的结果。请注意,返回的对象 (this.responsethis.optionGroup) 都没有您有兴趣调用的函数。

最简单的解决方案是删除returns。

于 2012-11-26T04:51:06.913 回答
0

不知道马特的回答是否明确,但是:

> return this.optionGroup;

表示函数返回optionGroup对象,而不是 . 引用的新对象this

构造函数this默认返回,所以没有 return 语句等价于:

return this;

功能相同Response

当然,假设您使用new.

于 2012-11-26T05:17:20.303 回答