当前位置: 代码迷 >> 综合 >> 每日一题:1.function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastNa
  详细解决方案

每日一题:1.function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastNa

热度:68   发布时间:2023-12-13 07:35:19.0

Question:如下输出什么?

function Person(firstName, lastName) {this.firstName = firstName;this.lastName = lastName;
}const member = new Person('Lydia', 'Hallie');
Person.getFullName = function() {return `${this.firstName} ${this.lastName}`;
};console.log(member.getFullName());
  • A: TypeError
  • B: SyntaxError
  • C: Lydia Hallie
  • D: undefined undefined

Answer:A

Analyze:

在JavaScript中,函数是一个对象,getFullName方法 会被添加到构造函数对象本身。 因此,我们可以调用Person.getFullName(),但是 member.getFullName() 会引发TypeError。

如果要使方法可用于所有对象实例,则必须将其添加到prototype属性:

Person.prototype.getFullName = function() {return `${this.firstName} ${this.lastName}`;
};

  相关解决方案