如何检查对象的属性是getter还是setter?

3
我在想HTML元素的textContent属性是否是一个getter,它会递归地搜索节点以查找文本节点。
我做了一个实验:

Object.defineProperty(HTMLElement.prototype, 'textContentMyOwnImplementation', {
 get() {
  const result = [];
  function search(node) {
   if(node.nodeName == '#text')
    result.push(node.data);
   else
    for(let i = 0; i < node.childNodes.length; i++) {
     search(node.childNodes[i]);
    }
  }
  search(this);
  return result.join(' ');
 }
})

结果与textContent相同。

这让我想到了一个问题。有没有办法确定一个属性是访问器还是不是访问器?

1个回答

8

是的,Object.getOwnPropertyDescriptor 方法与 defineProperty 相反:

const obj = {
  property: 'value',
  get accessor(){ return 'value' },
  set accessor(value){}
}

console.log(Object.getOwnPropertyDescriptor(object, 'property'))
/* 
{
  enumerable: true,
  writable: true,
  configurable: true,
  value: "value"
} 
*/

console.log(Object.getOwnPropertyDescriptor(object, 'accessor'))
/* 
{
  enumerable: true,
  writable: true,
  configurable: true,
  get: function(...){...},
  set: function(...){...}
} 
*/

通过这个,您可以实现一个函数来自动判断:

const isAccessor = (object, property) => !('value' in Object.getOwnPropertyDescriptor(object, property))

2
我只想补充一下,textContent 存在于 Node.prototype 上,因此您需要执行以下操作:Object.getOwnPropertyDescriptor(Node.prototype,'textContent') - ansavchenco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接