我有两个对象
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对象时,我可以看到对象中的字段,但是我看不到任何函数。
发生了什么事?
答案 0 :(得分: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.请注意,返回的对象(this.response
和this.optionGroup
)都没有您有兴趣调用的函数。
最简单的解决方案是删除return
。
答案 1 :(得分:0)
> return this.optionGroup;
表示函数返回optionGroup
对象,而不是this
引用的新对象。
构造函数默认返回this
,因此根本没有return语句等同于:
return this;
Response
函数相同。
当然假设您使用new
调用函数。