Can I enumerate properties that only exist as getter/setter functions?

Given a class like this

class Stuff {
  set b(v) {
  }
  get c() {
    return 'x'
  }
}

const x = new Stuff
console.log(x.hasOwnProperty('b'))

how can I test for "properties" b and c, or list all such getter/setters? hasOwnProperty does not show them to exist.

48 thoughts on “Can I enumerate properties that only exist as getter/setter functions?”

  1. Just like all properties defined with method syntax (whether getter/setter or not), they’re on the prototype, not the instance, so call hasOwnProperty on the prototype:

    class Stuff {
      set b(v) {
      }
      get c() {
        return 'x'
      }
      notGetter() {}
    }
    
    const x = new Stuff
    console.log(
      Object.getPrototypeOf(x).hasOwnProperty('b'),
      Stuff.prototype.hasOwnProperty('b')
    );
    
    const allGettersSetters = Object.entries(Object.getOwnPropertyDescriptors(Stuff.prototype))
      .filter(([, value]) => !value.hasOwnProperty('value'))
      .map(([key]) => key);
    console.log(allGettersSetters);
    Reply

Leave a Comment