gpt4 book ai didi

javascript - 为什么这个属性的 setter/getter 不起作用?

转载 作者:行者123 更新时间:2023-11-30 07:13:17 25 4
gpt4 key购买 nike

我正在尝试为 Person 上定义的属性添加 getter,因此我可以执行 test.fullName。问题是,当我记录 test.fullName 时,它是未定义的。为什么 setter/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);

最佳答案

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

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

仅向 Person 添加一个属性将使它成为静态的。您必须在 Person.prototype 上执行此操作。您可以在 MDN 阅读更多内容.根据链接:

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;

关于javascript - 为什么这个属性的 setter/getter 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43051545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com