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());
时间: 2024-03-03 15:53:22 浏览: 167
这段代码会抛出一个 TypeError 错误。因为 Person.getFullName 是在构造函数之外定义的,而在 JavaScript 中,只有在构造函数内部定义的属性和方法才会被添加到实例上。因此,调用 member.getFullName() 会抛出 TypeError 错误,因为 getFullName 方法并不存在于 member 实例中。要解决这个问题,可以将 getFullName 方法定义为 Person 构造函数的原型方法,如下所示:
```
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
}
const member = new Person("Lydia", "Hallie");
console.log(member.getFullName()); // "Lydia Hallie"
```
阅读全文