【问题标题】:Why can't "hasOwnProperty" be used on instanceof HTMLInputElement?为什么不能在 instanceof HTMLInputElement 上使用“hasOwnProperty”?
【发布时间】:2019-11-04 15:47:20
【问题描述】:

我想检查输入元素是复选框还是文本类型。

我知道我能做到:

//Type of input..
if ( input.type === "checkbox" ) 
//Contains the property..
if ( "checked" in input ) 

但我的问题是:为什么hasOwnProperty 返回 false?

我只想使用:

input.hasOwnProperty("checked")

但它每次都返回 false。

input 不是一个对象吗?
我不这么认为,但typeof 说是:

typeof input // returns "object" 

那是怎么回事?!

代码示例:

const input = document.querySelector("input")
 if ( input instanceof HTMLInputElement ) {
    console.dir(input);
    console.info(typeof input);
    console.log("with 'hasOwnProperty'",input.hasOwnProperty("checked"));
    console.log("with 'in'","checked" in input);
    console.log("with 'type'",input.type === "checkbox");
}
<input type="checkbox" />

The documentation about HTMLInputElement,只有类型复选框才有checked属性:

【问题讨论】:

  • checked 本身不是input 的成员;它是HTMLInputElement 原型的一部分。
  • 更具体地说,它是反映控件当前状态的getter,而不是HTMLInputElement 特定实例的属性。
  • 相关讨论:stackoverflow.com/questions/20381239/…(完全披露:我自己的回答)

标签: javascript hasownproperty


【解决方案1】:

"checked" in input 返回true,因为in 计算所有可枚举的属性。相反,.hasOwnProperty() 仅当属性是对象本身的成员时才会返回 true。如果它是继承的或对象的prototype 的成员,则返回false

在这种情况下,checkedHTMLInputElement.prototype 上的getter不是input 的成员。

const checkbox = document.getElementById("c");
const descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked');

console.log("'checked' is property of input:", "checked" in checkbox);
console.log("'checked' is own-property of input:", checkbox.hasOwnProperty("checked"));
console.log("'checked' is member of prototype:", HTMLInputElement.prototype.hasOwnProperty("checked"));
console.log("'checked' is getter:", descriptor.get !== undefined);
<input type="checkbox" id="c">

【讨论】:

  • 非常感谢 Tyler、Alnitak 和 apsillers !!
猜你喜欢
  • 2015-05-12
  • 2014-04-22
  • 2012-07-06
  • 2016-10-10
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
  • 2011-02-05
  • 2017-05-19
相关资源
最近更新 更多