如果你横切原型链,你会看到在底部(顶部?)是Object.prototype,因此我认为它们的行为会像普通对象一样。但是,当您通过console.dir在控制台中查看对象时,您将看到与该对象相关联的所有属性,Object.getOwnPropertyDescriptors不会为您提供这些属性。这怎么可能呢?
for (let property of Object.keys(Object.getOwnPropertyDescriptors(document))) {
console.log(property)
}
发布于 2019-09-19 13:35:40
问得好。这是因为HTMLElement上的许多属性实际上是getter和setter原型函数。
在DOM的幕后,有许多魔术在将几乎是英语的document.body.style = 'background: pink;'转换为渲染的图形更新。使用getters和setters可以帮助反应性模式,并消除成千上万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
*/https://stackoverflow.com/questions/58003924
复制相似问题