How To Console.log All Inherited Properties?
Solution 1:
When an object is printed through console.log
, it is printed with all its own properties and a link to the object it inherits from. You can see all the inherited properties in console, you just need to follow the prototype chain of the displayed object (typically using __proto__
or [[prototype]]
keys).
Solution 2:
When you use Object.create
then your prototype will be the same the object that you are inheriting, so, to show "father" properties you could see the prototype:
console.log(raleigh);
console.log(Object.getPrototypeOf(raleigh));
Maybe you will expect something more but I think that is the fast way to show that properties.
Solution 3:
Would this help? I'm throwing an alert, u can check the console as well!
var bike = {
wheels: 2,
};
var raleigh = Object.create(bike);
raleigh.color = 'red';
functiongetAllProperties( obj ) {
var properties = [];
do {
properties= properties.concat(Object.getOwnPropertyNames( obj ));
} while ( obj = Object.getPrototypeOf( obj ) );
return properties;
}
alert(getAllProperties(raleigh));
console.log(getAllProperties(raleigh));
Solution 4:
You could create a new Object especially for your log which has everything as own properties
functionflatten_inheritance(e) {
var o = Object.create(null), i, prop;
do {
prop = Object.getOwnPropertyNames(e);
for (i = 0; i < prop.length; ++i)
if (!(prop[i] in o))
o[prop[i]] = e[prop[i]];
} while (e = Object.getPrototypeOf(e));
return o;
}
flatten_inheritance(raleigh); // Object {color: "red", wheels: 2, valueOf, toString, etc..}
If you want to stop at Object.prototype
or some other prototype you can do this in the while
condition for example;
while (e = Object.getPrototypeOf(e) && e !== Object.prototype);
I would recommend you only do this when debugging rather than moving all your code away from inheritance though
Post a Comment for "How To Console.log All Inherited Properties?"