简体   繁体   中英

Why doesn't this getter for a property work?

I'm trying to add a getter for a property defined on Person , so I can do test.fullName . The problem is, when I log test.fullName , it's undefined. Why does the getter work properly?

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);

You have to define the property on the Person 's prototype property, so it's inherited on all instances.

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

Adding a property to just Person will make it static. You must do it on Person.prototype . You can read more at MDN . Per the link:

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

Thus, for all Person instances to inherit all properties such as fullName , define the property on Person.prototype .

Also, you are using commas instead semicolons. Use semicolons to terminate statements, not commas:

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

You're defining the fullName property on Person . You should define it on Person.prototype , so it's inherited by instances:

 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); 


Side note: Don't use commas where you should have semicolons, as in the Person constructor. I've fixed that above as well.

Define it on the prototype.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM