Setting an ES6 class getter to enumerable

ES6 style getters are defined on the prototype, not on each individual person. To set the greeting property to enumerable you need to change:

// Make enumerable (doesn't work)
Object.defineProperty(Person, 'greeting', {enumerable: true});

To:

// Make enumerable
Object.defineProperty(Person.prototype, 'greeting', {enumerable: true});

Object.keys only returns that object’s own enumerable properties, so properties on the prototype are not returned. You will find the greeting property in Object.keys( Object.getPrototypeOf( person ) ), or in a for…in loop. Updated Plunker

If instead, you want each individual instance of Person to have its own greeting you can define it in the constructor:

class Person {
  constructor(myName) {
    this.name = myName;

    Object.defineProperty( this, 'greeting', {
      enumerable: true,
      get: function ( ) { return `Hello, I'm ${this.name}`; }
    } );
  }
}

Updated Plunker

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)