【问题标题】:How to check if a property of an object is a getter or a setter?如何检查对象的属性是getter还是setter?
【发布时间】:2019-10-09 19:50:26
【问题描述】:

我想知道 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的一样。

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

【问题讨论】:

    标签: javascript object properties getter accessor


    【解决方案1】:

    是的。 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))
    

    【讨论】:

    • 我只想补充一点,textContentNode.prototype 上,因此您需要执行此操作:Object.getOwnPropertyDescriptor(Node.prototype, 'textContent')
    猜你喜欢
    • 2017-10-09
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2022-12-24
    • 2010-09-29
    • 1970-01-01
    相关资源
    最近更新 更多