>> […] lately, I've been reading that "document", "window" and other browser
>> objects are "host objects", and host objects have their own rules and
>> behaviors that depend on the browser and the platform. So it's possible
>> that merely testing "document.someFunctionality" can throw an exception
>> in some browser on some platform.
>>
>> So, in order to cover those cases, is it reasonable to do the following?
>>
>> if(typeof document.someProperty != 'undefined') {
>> // Go ahead and use the property
>> }
>>
>> if(typeof document.someFunction == 'function') {
>> // Go ahead and invoke "document.someFunction()"
>> }
>>
>> Or is it overkill?
>
> Quite the contrary.
>
> Some links for further reading:
>
> <
http://www.cinsoft.net/host.html>
> […]
I have since realized not only the usefulness of having a method that can
deal with separate object reference and property names instead of a `typeof'
result (isMethod), but also of having a separate method for methods of
host and native objects (isNativeMethod) each. (jsx.object.isMethodType(),
formerly isMethodType(), is still supported but has been marked deprecated
accordingly. It may not be supported in future revisions.)
Therefore, JSX:object.js contains jsx.object.isMethod()) (formerly
isMethod()) since at least revision 123 (2008-05-29), and
jsx.object.isHostMethod() (alias for .isMethod()) and
jsx.object.isNativeMethod() (wrapper for .isMethod()) since revision 234
(2011-12-12).
jsx.object.areNativeMethods(), jsx.object.areHostMethods(), and
jsx.object.areMethods(), the latter of which has been been introduced in
revision 146 (2009-07-16), are aliases for those methods, respectively. As
an extension to the methods in David's library (so to speak), they also
support calls of the form
if (jsx.object.isHostMethod(window, "document", "write"))
(accepts an arbitrary number of arguments) which prevents you from having to
write
if (typeof window.document != "undefined"
&& jsx.object.isHostMethod(window.document, "write"))
and
if (jsx.object.areHostMethods(document, ["open", "write", "close"]))
which prevents you from having to write
var _isHostMethod = jsx.object.isHostMethod;
if (_isHostMethod(document, "open")
&& _isHostMethod(document, "write")
&& _isHostMethod(document, "close"))
which is not only tedious to write but also inefficient by comparison.
See
<
http://PointedEars.de/websvn/filedetails.php?repname=JSX&path=%2Ftrunk%2Fobject.js>
for more.
PointedEars
--
> If you get a bunch of authors […] that state the same "best practices"
> in any programming language, then you can bet who is wrong or right...
Not with javascript. Nonsense propagates like wildfire in this field.
-- Richard Cornford, comp.lang.javascript, 2011-11-14