Javascript工厂功能无法正常工作

时间:2017-03-29 06:10:11

标签: javascript function

根据教程我看这段代码应该回归" 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;

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

缺少对象键功能。你只是在对象中没有提及对象功能的对象。所以提到对象键的功能名称。

像这样

 1. person.getFullName();// for function call
 2. person.firstName 
 3. person.lastName

更多了解refer this article

&#13;
&#13;
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();
&#13;
<p id="para"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

function createPerson(firstName, lastName) {
  return {
    firstName: firstName,
    lastName: lastName,
    getFullName: function() {
      return this.firstName + " " + this.lastName;
    }
  };
}

var person = createPerson(&#34; John&#34;,&#34; Doe&#34;);

  

它只返回&#34; [object,Object]&#34;

因为人是那里的对象

document.getElementById("para").innerHTML = person;

如果你想打印名字

document.getElementById("para").innerHTML = person.firstName 

如果您想要打印lastName

document.getElementById("para").innerHTML = person.lastName 

如果你想打印全名

document.getElementById("para").innerHTML = person.getFullName() 

不是你必须调用该函数的最后一个。