如果横向浏览原型链,您会在底部(top?)看到Object.prototype
,因此我认为它们的行为类似于普通对象。但是,Object.getOwnPropertyDescriptors
不会为您提供一个具有通过console.dir
在控制台中查看该对象时将与该对象关联的所有属性的对象。怎么会这样?
for (let property of Object.keys(Object.getOwnPropertyDescriptors(document))) {
console.log(property)
}
最佳答案
好问题。这是因为HTMLElement
上的许多属性实际上是getter和setter原型函数。
DOM幕后发生了很多魔术,将几乎是英语的document.body.style = 'background: pink;'
变成了渲染的图形更新。使用吸气剂和塞特剂有助于反应性模式,并消除了成千上万个HTMLElement
上的冗余属性构造所造成的内存浪费。
例:
// 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
*/
关于javascript - 为什么Object.getOwnPropertyDescriptors在HTMLElements上不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58003924/