Dino.F
Dino.F

Reputation: 91

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

Upvotes: 1

Views: 68

Answers (3)

Andrew Li
Andrew Li

Reputation: 57974

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;

Upvotes: 5

Pytth
Pytth

Reputation: 4176

Define it on the prototype.

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075169

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.

Upvotes: 4

Related Questions