简体   繁体   中英

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

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?

Yes. The Object.getOwnPropertyDescriptor method does the oppesite 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM