为什么不能在instanceof HTMLInputElement上使用“ hasOwnProperty”?

Joe*_*uño 6 javascript hasownproperty

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

我知道我可以这样做:

//Type of input..
if ( input.type === "checkbox" ) 
//Contains the property..
if ( "checked" in input ) 
Run Code Online (Sandbox Code Playgroud)

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

我只想使用:

input.hasOwnProperty("checked")
Run Code Online (Sandbox Code Playgroud)

但每次都会返回false。

不是input物体吗?
我不这么认为,但是typeof说是:

typeof input // returns "object" 
Run Code Online (Sandbox Code Playgroud)

那么发生了什么?!

代码示例:

//Type of input..
if ( input.type === "checkbox" ) 
//Contains the property..
if ( "checked" in input ) 
Run Code Online (Sandbox Code Playgroud)
input.hasOwnProperty("checked")
Run Code Online (Sandbox Code Playgroud)

有关HTMLInputElement的文档,只有type复选框具有以下属性checked

Tyl*_*per 5

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

在这种情况下,checked是一个吸气剂HTMLInputElement.prototype的成员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);
Run Code Online (Sandbox Code Playgroud)
<input type="checkbox" id="c">
Run Code Online (Sandbox Code Playgroud)