根据我正在观看的教程,这段代码应该返回“John Doe”。目前,它只返回“[object, Object]”,我做错了什么?
<p id="para"></p>
function createPerson(firstName, lastName) {
return {
firstName: firstName,
lastName: lastName,
getFullName: function() {
return this.firstName + " " + this.lastName;
}
};
}
var person = createPerson("John", "Doe");
document.getElementById("para").innerHTML = person;
有什么想法吗?
最佳答案
缺少对象键功能。您只发布对象而未提及对象中的功能。因此请提及对象键的功能名称。
像这样
1. person.getFullName();// for function call
2. person.firstName
3. person.lastName
function createPerson(firstName, lastName) {
return {
firstName: firstName,
lastName: lastName,
getFullName: function() {
return this.firstName + " " + this.lastName;
}
};
}
var person = createPerson("John", "Doe");
document.getElementById("para").innerHTML = person.getFullName();
<p id="para"></p>
关于Javascript 工厂函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43085632/