![](/img/trans.png)
[英]Why setter/getter definition in .assign object merge doesn't work?
[英]Why doesn't this getter for a property work?
我正在嘗試為Person
定義的屬性添加吸氣劑,因此可以執行test.fullName
。 問題是,當我登錄test.fullName
,它是未定義的。 為什么吸氣劑能正常工作?
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
的prototype屬性上定義該屬性,以便在所有實例上繼承該屬性。
Object.defineProperty(Person.prototype, 'fullName', {
get: function() {
return this.name +' '+ this.surname
}
});
僅向Person
添加屬性將使其靜態。 您必須在Person.prototype
上執行此Person.prototype
。 您可以在MDN上閱讀更多內容。 每個鏈接:
原型是JavaScript對象彼此繼承特征的機制
因此, Person.prototype
所有Person
實例繼承所有屬性(例如fullName
,請在Person.prototype
上定義屬性。
另外,您使用逗號代替分號。 使用分號來終止語句,而不是逗號:
this.name = name;
this.surname = surname;
this.yearOfBirth = yearOfBirth;
您要在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
構造函數中那樣。 我也已將其修復。
在原型上定義它。
Object.defineProperty(Person.prototype, 'fullName', {
get() {
return `${this.name} ${this.surname}`;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.