簡體   English   中英

為什么此吸氣劑不能用於房地產工作?

[英]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);

您必須在Personprototype屬性上定義該屬性,以便在所有實例上繼承該屬性。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM