Now, we will not get private variables this way because they are not available.
Use a for..in loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.
To avoid including inherited properties in our enumeration, check
hasOwnProperty(), and this is why we should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using
The standard way, which has already been proposed several times is:
If will alert "12" in all browsers except IE. IE will simply ignore this key. The affected key values are:
To be really safe in IE we have to use something like:
The good news is that EcmaScript 5 defines the Object.keys(myObject) function, which returns the keys of an object as array and some browsers (e.g. Safarwe 4) already implement it.
In modern browsers (ECMAScript 5) to get all enumerable properties we can do: Object.keys(obj) (Check the link to get a snippet for backward compatibility on older browsers) Or to get also non-enumerable properties: Object.getOwnPropertyNames(obj) Check ECMAScript 5 compatibility table
WE think an example of the case that has caught me by surprise is relevant:
But to my surprise, the output is
Why? Another script on the page has extended the Object prototype: