https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Defining_getters_and_setters
Enumerating all properties of an object
Starting with
ECMAScript 5, there are three native ways to list/traverse object properties:
- for...in loops
This method traverses all enumerable properties of an object and its prototype chain
- Object.keys(o)
This method returns an array with all the own (not in the prototype chain) enumerable properties names ("keys") of an object o
.
- Object.getOwnPropertyNames(o)
This method returns an array containing all own properties names (enumerable or not) of an object o
.
In ECMAScript 5, there is no native way to list all properties of an
object. However, this can be achieved with the following function:
- function listAllProperties(o){
- var objectToInspect;
- var result = [];
-
- for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){
- result = result.concat(Object.getOwnPropertyNames(objectToInspect));
- }
-
- return result;
- }
This can be useful to reveal "hidden" properties (properties in the
prototype chain which are not accessible through the object, because
another property has the same name earlier in the prototype chain).
Listing accessible properties only can easily be done by removing
duplicates in the array.
No comments:
Post a Comment