11

I'm trying to iterate over all methods in a JavaScript pseudoclass and can easily tell if something is a method or not with (obj.member instanceof Function), however I'm trying to include methods that may be hidden from a for...in loop via defineProperty with an enumerable flag set to false - how do I iterate all members of a pseudoclass, regardless of the enumerable value?

CoryG
  • 2,429
  • 3
  • 25
  • 60

1 Answers1

13

You can always use Object.getOwnPropertyNames, which will include non-enumerable properties as well. However, this will not include properties from prototypes, so if you are asking about "pseudoclass instances" you might need to loop the prototype chain with Object.getPrototypeOf.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    Correction, in 8 minutes you can have some karma - damned site think's I'm a bot or something. – CoryG Feb 26 '13 at 16:29
  • what if, in inspection, I can see a property but it doesn't apear under `getOwnPropertyNames` nor `keys`? Example: `typeof obj['stuff'] == 'function'; Object.getOwnPropertyNames(this).indexOf('stuff') == -1`. This happened on an ES6 class, babelified. – igorsantos07 Aug 24 '16 at 04:34
  • @igorsantos07: as the answer says, it's likely an inherited property. Try `Object.getOwnPropertyNames(Object.getPrototypeOf(this))`, or use a complete loop. – Bergi Aug 24 '16 at 04:42
  • whoa. that's confusing. it seems from the object instance I need to use getPrototypeOf to get to the actual defined class. might be some sort of effect from using Babel to transpile code :| – igorsantos07 Aug 24 '16 at 04:56
  • @igorsantos07: No, that's how prototypes worked since the beginning, even without ES6 or Babel. – Bergi Aug 24 '16 at 04:58
  • so getOwnPropertyNames won't include properties from prototypes nor properties defined by its own class, right? – igorsantos07 Aug 24 '16 at 04:59
  • @igorsantos07 I'm not sure what you mean by "its own class". Every instance inherits the shared class methods from the prototype object. Only instance-specific data is stored in own properties. – Bergi Aug 24 '16 at 05:01
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/121685/discussion-between-igorsantos07-and-bergi). – igorsantos07 Aug 24 '16 at 05:02
  • 1
    The [following link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) might be relevant here. – x-yuri Aug 19 '21 at 19:45