How to list all properties(methods and attributes) in an object and it's prototype chain? I'm interested in all of them (enumerable, and not enumerable).
Target browser - chrome.
How to list all properties(methods and attributes) in an object and it's prototype chain? I'm interested in all of them (enumerable, and not enumerable).
Target browser - chrome.
This:
for(var k in obj) {
console.log(k, obj[k]) // name, value
}
Example:
var obj1 = { a: 10, b: "x", c: { no: "no" }}
var obj2 = new Object(obj1)
obj2.d = "yes"
for (var k in obj2) {
console.log(k, obj2[k]) // name, value
}
I'm interested in all of them (enumerable, and not enumerable).
You can't enumerate what's not enumerable. Actually you can define not enumerable properties to avoid them appear as part of an iterator like a for...in
or Object.keys
. See this other Q&A to learn more about a workaround: Is it possible to get the non-enumerable inherited property names of an object?
For now, the easiest way of iterating all properties, both own properties and prototype's properties is using a for...in
loop:
for(var propertyName in obj) {
}
And you can use Object.hasOwnProperty
to check if a property isn't declared on the given object prototype:
for(var propertyName in obj) {
if(obj.hasOwnProperty(propertyName)) {
// It's not from the object's prototype...
}
}