Ignore the error. The "in" operator is clearly defined in ECMA 262-5.1 / June 2011 sec-11.8.7
There appear to be only three outcomes for 'someProperty' in anObject
which is one of: true
, false
, or a TypeError
exception is thrown. When it evaluates to true
, then there is definitely 'someProperty' in anObject
. When it evaluates to false
there is definitely not 'someProperty' in anObject
. When a TypeError
is thrown there is definitely not 'someProperty' in anObject
because anObject
is either null or it isn't an object at all. This all seems very clear to me. When I want to know if an object has a property and, I don't care if that property is the object's own property or being inherited and, I don't care what the value of the property is, then I simply look for 'someProperty' in anObject
.
Warning
Caution: some would have you check for anObject.someProperty !== undefined
but that isn't really checking whether or not the object has the property. What it's doing is checking whether the object has the property AND that the value of that property is NOT undefined. Some would have you check for anObject.hasOwnProperty('someProperty');
but that will only tell you if the object has that property AND has NOT inherited it somehow. Don't believe me? Try the following:
console.log(document.body.tagName);
// BODY
console.log(document.body.hasOwnProperty('tagName'));
// false, it's inherited
console.log('tagName' in document.body);
// true, it does have the property
document.body.wobbles = undefined;
// new property added to document.body
console.log('wobbles' in document.body);
// true, it does have the property
console.log(document.body.wobbles !== undefined);
// false, the value really IS undefined
I've written an article about the "in" operator that goes into more detail. If you want to read it it's at: http://matthewkastor.blogspot.com/2012/09/Unexpected--in---Compare-with-undefined--or-use-the-hasOwnProperty-method-instead.html The bottom line is that you should just ignore this error and wrap things up in a try catch block if the object might be null or not an object.
function hasProperty(prop, obj) {
try {
return prop in obj;
} catch(e) {
return e;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…