Reputation: 888
If you transverse the prototype chain, you'll see at the bottom (top?) is Object.prototype
, therefore I figured they would behave like ordinary objects. However, Object.getOwnPropertyDescriptors
does not give you an object with all the properties you'll see associated with the object when viewing it in the console via console.dir
. How can this be?
for (let property of Object.keys(Object.getOwnPropertyDescriptors(document))) {
console.log(property)
}
Upvotes: 0
Views: 192
Reputation: 520
Good question. This is because many of the properties on HTMLElement
's are actually getter and setter prototype functions.
There's a lot of magic going on behind the curtain of the DOM to turn the almost-English document.body.style = 'background: pink;'
into a rendered graphics update. Using getters & setters aids reactivity patterns and removes the memory waste of redundant property construction on thousands of HTMLElement
's.
Example:
// Class with prototype getter
class Thing {
constructor() {
this.year = new Date().getFullYear()
}
get time() {
return Date.now();
}
}
console.dir(new Thing());
// > Prints a JSON representation including `Thing#time` and `Thing#year`
console.log(Object.getOwnPropertyDescriptors(new Thing()));
/*
> Prints an object with *only* the `#year` descriptor
because `#time` is a prototype function, not a property
*/
Upvotes: 2