How to check if a property of an object is a getter or a setter?

Viewed 1017

I was wondering if textContent property of an HTML element is a getter that's searching through nodes recursively to find text nodes.

I did an experiment:

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(' ');
 }
})

The result is the same as textContent's.

This brought me to a question. Is there any way to determine whether a property is an accessor or not?

1 Answers

Yes. The Object.getOwnPropertyDescriptor method does the opposite of 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(...){...}
} 
*/

Using this, you can implement a function, that determines that for you:

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