clever blog title

clever blog subtitle

Subscribe to RSS feed

Posts tagged with "function"

(not really a) A standards-compliant, cross-browser, reliable way to detect functions in JS (thanks to IE, again)

, ,

Edit: Turns out this doesn't work for some native functions such as window.alert in IE. It fails exactly where the typeof operator fails :-P.

A lot of scripts rely on Function.prototype.toString to determine if an object is a function in Javascript. This is not compatible with many mobile browsers, which don't support function decompile (optional according to ECMA-262) for performance reasons.

According to page 103 of ECMA-262 3rd Edition:

15.2.4.2 Object.prototype.toString ( )
When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings "[object ", Result(1), and "]".
3. Return Result(2).


This gives us a really easy way to know if something is a function in any ECMA-262 compliant browser (including IE, Firefox, Safari, and Opera):
function isFunction(x) {
  return Object.prototype.toString.call(x) == '[object Function]';
};
May 2013
S M T W T F S
April 2013June 2013
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 30 31