Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't "hasOwnProperty" be used on instanceof HTMLInputElement?

I want to check if an input element is a checkbox or text type.

I know I can do this:

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

But my question is: why do hasOwnProperty returns false?

I just want to use:

input.hasOwnProperty("checked")

but it returns false everytime.

Isn't input an object?
I don't think so, but typeof said it is:

typeof input // returns "object" 

So what is going on?!

Code example:

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, only type checkbox have the property checked:

like image 348
Joel Garcia Nuño Avatar asked Nov 04 '19 15:11

Joel Garcia Nuño


People also ask

What does hasOwnProperty method do?

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Is hasOwnProperty necessary?

Then no, you don't need to use the hasOwnProperty() . But the full control over the environment is not something you should count on. It's fine to drop the hasOwnProperty() only until someone somewhere redefines the Object type. Before or even after your script is started.


1 Answers

"checked" in input returns true because in evaluates all enumerable properties. On the contrary, .hasOwnProperty() will return true only if the property is a member of the object itself. It returns false if it's inherited or a member of the object's prototype.

In this case, checked is a getter on the HTMLInputElement.prototype, not a member of 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">
like image 167
Tyler Roper Avatar answered Sep 18 '22 14:09

Tyler Roper