0

I have two objects

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;
}

However, when I try and call any of the functions that I've created, console tells me that said object does not have such a function. When I print out a Response or OptionGroup object in console, I can see the fields in the objects, but I cannot see any of the functions.

What is going on?

praks5432
  • 7,246
  • 32
  • 91
  • 156

2 Answers2

2

When you return something from an object used as a constructor, as the above code does, that value is the result of the new call. Note that neither returned object (this.response and this.optionGroup) has the functions you're interested in calling.

The simplest solution is to remove the returns.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

Dunno if Matt's answer was clear, but:

> return this.optionGroup;

means the function returns the optionGroup object, not the new object referenced by this.

Constructors return this by default, so no return statement at all is equivalent to:

return this;

Same for the Response function.

Assuming of course that you are calling the functions with new.

RobG
  • 142,382
  • 31
  • 172
  • 209