How to verify if object has specific property without the operator "in"?

Asked

Viewed 47 times

2

Some browsers do not support inputMode, like Safari. So to then mitigate the situation, I would have another behavior if the inputMode existed or not.

Searching I found the operator in:

if ("inputMode" in document.querySelector("input")) {
  console.log("Existe inputMode no <input>")
}
<input>

It works. The problem is, since I’m using another language, I have no way to call the operator in (well I would have, but it would be a significantly bigger job just for that).


Is there any function that does the same as the in?

How can I have the same behavior as in without using this specific operator? Using any function (other than eval, obviously).

  • I just don’t quite understand why you can’t use the in. Could you explain it a little better? I was curious.

  • 2

    I’m using Golang, and compiling for Webassembly. Then the querySelector becomes: js.Global().Get("document").Call("querySelector", "input"). I only have access to .Call, .Invoke and .InstanceOf (...), but you don’t have any .In. So I don’t assume there’s no way to use the in. The functions I have access to are those. The "most difficult method" would be to create a Callimport to call my JS function inside the Golang, something like that from here. I withheld that information because it would make everything more confusing.

1 answer

3


You can use the function Reflect.has, which has the same operation as the operator in, only in a qualified function format in the overall object Reflect.

So:

if (Reflect.has(document.querySelector("input"), "inputMode")) {
  console.log(1);
}

It is worth remembering that the operator in (and therefore Reflect.has) are different from Object.prototype.hasOwnProperty. Learn more in this other answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.