Peter Michaux's
feature detection article really saved my bacon.
I recently had to debug some IE 7 ++ bugs in our JavaScript API. I found some crusty functions that were supposed to determine if a function or property exists on a loaded plugin object (ActiveX in IE, NPAPI otherwise). The functions were returning a false negative in IE 7 or newer
unless users turned on compatibility mode.
Since we already had Prototype as a requirement, I figured I'd use their
isFunction. The logic worked fine on browsers other than IE :(
Logically, all the well-known JavaScript frameworks' implementations of
isFunction are highly optimized and may not work as expected with bipolar JavaScript host objects (e.g. plugins, window, document, alert), at least on IE.
Michaux's approach was clean and worked consistently for our needs across all our supported browsers. Note: I never saw the "else" code path exercised, but left it in.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 | /* Check to see if a property (function or field) is defined for the given object.
* This function is reliable for native and host objects.
* @param object {Object} - the object to test.
* @param propertyName {String} - name of the property to test.
* @type Boolean
* @return true - if property is defined, False otherwise.
*/
_propertyExists: function( object, property ) {
//tweaked version of Michaux's detection function:
//http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
var isProperty = false;
var theType = typeof object[property];
if( theType != 'undefined' ) {
isProperty = true;
}
else {
try {
// This test would error for ActiveX but
// those test will have returned above
// because typeof result will have been
// 'unknown'.
if( object[property] ) {
isProperty = true;
}
}
catch (e) {}
}
return isProperty;
},
|