Javascript的新手在尝试更好地使用这种语言进行编码。所以我试图创建一个应该是牙科诊所的对象。在那个诊所的对象里,我想要在那里工作的所有牙医的阵列。牙医也是对象(因此对象内部的对象)。当我尝试添加/访问对象时,它们是未定义的,它告诉我它们具有的方法不存在。我不确定错误可能是什么,从我使用Java的时候开始就习惯用这种方式进行编码。 谁能签出代码并为我指出正确的方向?寻求帮助。
function createDentistObject(firstName, lastName, age)
{
let dentistObject =
{
firstName: firstName, lastName: lastName, age:age,
getFullName: function()
{
return this.firstName + " " + this.lastName;
}
};
}
function createDentistList()
{
let dentistList = [(createDentistObject("Test","Test",0))];
return dentistList;
}
let myDentalClinic =
{
dentists:createDentistList(),
addDentist:function(dentistObject)
{
console.log("Dentistfullname: " + this.dentistObject.getFullName());
if(this.dentists.length == 0)
{
this.dentists.push(this.dentistObject);
}
else
{
/*if(this.dentistExist(dentistObject))
{
console.log("Dentist exists in the list!");
}*/
this.dentists.push(dentistObject);
}
},
dentistExist:function(dentistObject)
{
for(let i = 0; i < this.dentists.length; i++)
{
if(this.dentists[i].firstName === dentistObject.firstName)
{
return true;
}
}
return false;
},
printAllDentists:function()
{
let output = "";
for(let i = 0; i < this.dentists.length; i++)
{
output += this.dentists[i].firstName + "\n";
}
console.log(output);
console.log(this.dentists);
}
};
let dentistTest = createDentistObject("Dentist", "Dentiston", 38);
myDentalClinic.addDentist(dentistTest);
答案 0 :(得分:1)
您忘记了在第一个函数中返回创建的牙医对象:
function createDentistObject(firstName, lastName, age)
{
let dentistObject =
{
firstName: firstName, lastName: lastName, age:age,
getFullName: function()
{
return this.firstName + " " + this.lastName;
}
};
return dentistObject;
}
在myDentalClinic对象中,您还使用this.dentistObject而不是您的参数ististObject键入了一些错字。固定:
let myDentalClinic =
{
dentists:createDentistList(),
addDentist:function(dentistObject)
{
console.log("Dentistfullname: " + dentistObject.getFullName());
if(this.dentists.length == 0)
{
this.dentists.push(dentistObject);
}
else
{
/*if(this.dentistExist(dentistObject))
{
console.log("Dentist exists in the list!");
}*/
this.dentists.push(dentistObject);
}
},
dentistExist:function(dentistObject)
{
for(let i = 0; i < this.dentists.length; i++)
{
if(this.dentists[i].firstName === dentistObject.firstName)
{
return true;
}
}
return false;
},
printAllDentists:function()
{
let output = "";
for(let i = 0; i < this.dentists.length; i++)
{
output += this.dentists[i].firstName + "\n";
}
console.log(output);
console.log(this.dentists);
}
};