0

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?

Community
  • 1
  • 1
Bakudan
  • 19,134
  • 9
  • 53
  • 73

2 Answers2

3

String is a constructor function, and functions are also objects. You can append properties to it.

For example:

function foo(){
    alert('from foo');
}

foo.bar = function(){
    alert('bar on foo');
}

foo();     //from foo
foo.bar(); //bar on foo

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.link is accessing a property of the constructor function itself - which does not exist.

  • using String.prototype.link accesses the link() function that comes with every string - which does exist (and which you should use)

Joseph
  • 117,725
  • 30
  • 181
  • 234
  • I thought about it, [this](http://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript) actually helped, and actually `typeof String().link === 'function'` returns true. This way String will create an empty object and link "availability" should be checked against it. – Bakudan May 10 '12 at 03:56
  • @Milo but you'd be creating an object just to check for `link` rather than check for `link` directly in the prototype. – Joseph May 10 '12 at 04:33
  • Oh, I didn't think in that way! This is more practical. – Bakudan May 12 '12 at 03:01
0

Because string is the Object and doesn't have the link() method. Only the strings have this method. Look:

String//Defines the Object
String.prototype//Defines the methods and properties that will be bound to a var of the type String
'foo'//This is a string
'foo'.link//So it has the link method
String//This is an Objecy that defines the strings
String.link//So it doesn't have the link method
String.prototype//An object that stores the methods and properties of the vars of type String
String.prototype.link//So it has the link method
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67