Unusual if (a in b) JavaScript syntax?
I have just stumbled upon the following webpage and am somewhat intrigued by the use of the in
keyword.
http://diveintohtml5.ep.io/examples/input-autofocus-with-fallback.html
- Is this valid JavaScript?
- Do all browsers accept this?
- How does it actually work?
They are using this syntax for fallback when web browser doesn't support the autofocu开发者_JAVA技巧s
attribute. So this would lead me to believe that this syntax is valid.
The in
operator checks if a property is defined on an object. So, this is valid Javascript and is accepted in almost all browsers.
In this case, the code is checking if "autofocus" is a property of a new element. If it is, then most likely the browser supports autofocus
and will not need .focus()
(or someone may be extending prototypes).
You can think of it like this:
"localStorage" in window; // true
!!window["localStorage"]; // true
window["localStorage"] !== undefined; // true
These statements are basically the same.
"autofocus" is an arbitrary boolean attibute that the script looks for. It's really no different than <input id="q" class="autofocus">
, except in this case, the script would need to look for the class name (which a lot of validation scripts usually use) versus the attribute.
The browser doesn't "support" it, the script makes it work.
精彩评论