The answers from this question says to use this to check if function is defined:
typeof yourFunction === 'function'
But I’ve tried this on a non-standard function link(). And actually this returned false. The function is available on every browser I’ve tried – IE, Chrome, Opera, FireFox.
typeof String.link === 'function' // false
typeof String.link() === 'function' // Uncaught error ...
Then somewhere I find:
typeof String.prototype.link === 'function' //true
which actually returns true. What is the difference and why the first one fails?
Stringis a constructor function, and functions are also objects. You can append properties to it.For example:
It’s the same reason how jQuery’s
$acts like an object (eg.$.each()) and like a function as well (eg.$(selector)).And so:
using
String.linkis accessing a property of the constructor function itself – which does not exist.using
String.prototype.linkaccesses thelink()function that comes with every string – which does exist (and which you should use)