为什么 getter 对于 属性 不起作用?

Why doesn't this getter for a property work?

我正在尝试为 Person 上定义的 属性 添加 getter,这样我就可以 test.fullName。问题是,当我记录 test.fullName 时,它是未定义的。为什么 getter 可以正常工作?

function Person(name, surname, yearOfBirth){
this.name = name,
this.surname = surname,
this.yearOfBirth = yearOfBirth };

Object.defineProperty(Person, 'fullName', {
    get: function(){
        return this.name +' '+ this.surname
    }
});

var test = new Person("test", "test", 9999);
console.log(test.fullName);

您正在 Person 上定义 fullName 属性。你应该在 Person.prototype 上定义它,所以它被实例继承:

function Person(name, surname, yearOfBirth) {
    this.name = name;
    this.surname = surname;
    this.yearOfBirth = yearOfBirth;
};

Object.defineProperty(Person.prototype, 'fullName', {
    get: function() {
        return this.name + ' ' + this.surname
    }
});

var test = new Person("test", "test", 9999);
console.log(test.fullName);


旁注:不要在应该有分号的地方使用逗号,就像在 Person 构造函数中那样。我也在上面修复了这个问题。

您必须在 Person 原型 属性 上定义 属性,因此它会在所有实例上继承。

Object.defineProperty(Person.prototype, 'fullName', {
    get: function() {
        return this.name +' '+ this.surname
    }
});

将 属性 添加到 Person 将使它成为静态的。您必须在 Person.prototype 上完成。您可以在 MDN 阅读更多内容。根据 link:

Prototypes are the mechanism by which JavaScript objects inherit features from one another

因此,为了让所有Person实例继承fullName等所有属性,在Person.prototype上定义属性。

此外,您使用的是逗号而不是分号。使用分号来终止语句,而不是逗号:

this.name = name;
this.surname = surname;
this.yearOfBirth = yearOfBirth;

在原型上定义它。

Object.defineProperty(Person.prototype, 'fullName', {
    get() {
        return `${this.name} ${this.surname}`;
    }
});