首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么Object.getOwnPropertyDescriptors不能在HTMLElements上工作?

为什么Object.getOwnPropertyDescriptors不能在HTMLElements上工作?
EN

Stack Overflow用户
提问于 2019-09-19 12:51:29
回答 1查看 54关注 0票数 0

如果你横切原型链,你会看到在底部(顶部?)是Object.prototype,因此我认为它们的行为会像普通对象一样。但是,当您通过console.dir在控制台中查看对象时,您将看到与该对象相关联的所有属性,Object.getOwnPropertyDescriptors不会为您提供这些属性。这怎么可能呢?

代码语言:javascript
复制
for (let property of Object.keys(Object.getOwnPropertyDescriptors(document))) {
  console.log(property)
}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-19 13:35:40

问得好。这是因为HTMLElement上的许多属性实际上是gettersetter原型函数。

DOM的幕后,有许多魔术在将几乎是英语的document.body.style = 'background: pink;'转换为渲染的图形更新。使用getters和setters可以帮助反应性模式,并消除成千上万HTMLElement上冗余属性构造造成的内存浪费。

示例:

代码语言:javascript
复制
// 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
*/
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58003924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档