In JavaScript we have a few ways of getting the properties of an object, depending on what we want to get.
1) Object.keys()
, which returns all own, enumerable properties of an object, an ECMA5 method.
2) a for...in
loop, which returns all the enumerable properties of an object, regardless of whether they are own properties, or inherited from the prototype chain.
3) Object.getOwnPropertyNames(obj)
which returns all own properties of an object, enumerable or not.
We also have such methods as hasOwnProperty(prop)
lets us check if a property is inherited or actually belongs to that object, and propertyIsEnumerable(prop)
which, as the name suggests, lets us check if a property is enumerable.
With all these options, there is no way to get a non-enumerable, non-own property of an object, which is what I want to do. Is there any way to do this? In other words, can I somehow get a list of the inherited non-enumerable properties?
Thank you.
Taking advantage of Sets leads to a somewhat cleaner solution, IMO.
Since
getOwnPropertyNames
can get you non-enumerable properties, you can use that and combine it with walking up the prototype chain.I tested that on Safari 5.1 and got
Update: Refactored the code a bit (added spaces, and curly braces, and improved the function name):
And to simply get everything..(enum/nonenum, self/inherited.. Please confirm..
Here is the solution that I came up with while studying the subject. To get all non-enumerable non-own properties of the
obj
object dogetProperties(obj, "nonown", "nonenum");
Example of using:
To get all inherited properties or methods for some instance you could use something like this
if you are trying to log non enumerable properties of a parent object ex. by default the methods defined inside a class in es6 are set on prototype but are set as non-enumerable.