Re: 'in' operator and feature detection technique...
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: 'in' operator and feature detection technique...

From: VK <schools_ring@yahoo.com>
Date: Thu Feb 09 2006 - 17:46:28 CET

Luke Matuszewski wrote:
> We all know that feature detection technique works from very beggining
> of user-agents supporting JavaScript. We can alway check if eg.
> document has a write property or smth else:
>
> if(document.write) {
>
> }
>
> We could do that for all of objects, so i have been surprised when i
> found 'in' operator, which for above example would be used like this:
>
> if("write" in document) {
>
> }
>
> So i have questioned myself what for ? I can always do:
>
> if(document["write"]) {
>
> }
>
> or even
> var prop = [...];
>
> if(document[prop]) {
>
> }
>
> which is supported better then 'in' operator ('in' is supported since
> W. IE 5.5 and NN 6 - around 2000 year). I can only guess that 'in' was
> provided in W. IE 5.5 only for convenience... but that is my guess and
> someone more knowlegable could write here some more opinions on this
> operator...

('property' in someObject) is not intended for features test - though
it can be used and it is used this way (when the support for
prehistoric browsers is not a requirement).

But originally it was introduced with it counterpair hasOwnProperty for
prototype-based inheritance management.

This very primitive sample you can play with is rather
self-explanatory.

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type"
 content="text/html; charset=windows-1251">
<script type="text/javascript">

var myObject = new Object();
myObject.constructor.prototype.p1 = true;
myObject.p2 = true;

alert('p1' in myObject); // true
alert('p2' in myObject); // true

alert(myObject.hasOwnProperty('p1')); // false
alert(myObject.hasOwnProperty('p2')); // true
</script>
</head>

<body>

</body>
</html>

P.S.
The "in" operator checks if an object has a property named property. It
also checks the object's prototype to see if the property is part of
the prototype chain.

The "hasOwnProperty" method returns true if object has a property of
the specified name, false if it does not. This method does not check if
the property exists in the object's prototype chain; the property must
be a member of the object itself.
Received on Mon May 1 03:12:22 2006