Alex
Alex

Reputation: 171

How do I get a getter property in a class appear when calling Object.keys()?

class cat {
 constructor(first, last) {
   this.firstname = firstname;
   this.lastname = last;
 }
 get fullname() {
   return this.firstname + " " + this.lastname;
 }

}

let homeCat = new Cat("Bella", "Boo");

I'm creating a class similar to up above. How do I get homeCat.fullname to appear in the property list when calling Object.keys(homeCat)?

Upvotes: 0

Views: 542

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386736

You could define a property for this and make it enumerable.

class Cat {
   constructor(first, last) {
       this.firstname = first;
       this.lastname = last;
       Object.defineProperty(this, 'fullname', {
           get () {
               return this.firstname + " " + this.lastname;
           },
           enumerable: true
       });
   }
}


let homeCat = new Cat("Bella", "Boo");

console.log(homeCat.fullname);
console.log(Object.keys(homeCat));

Upvotes: 2

Related Questions