Page 1 of 1

JavaScript Function detection?

Posted: Thu Jan 29, 2009 2:52 pm
by JAB Creations
Does JavaScript support function detection?

Like if (this_function()) {alert('function exists!');}?

Re: JavaScript Function detection?

Posted: Thu Jan 29, 2009 3:03 pm
by pickle
Usually you can just do:

Code: Select all

if(this_function)

Re: JavaScript Function detection?

Posted: Thu Jan 29, 2009 3:32 pm
by JAB Creations
AH! Ok! I was adding the parenthesis like if (function_1())...the following code is not my style but it works. Thanks!

Code: Select all

<script>function hello() {alert('hello');}function test() {if (hello) {alert('exists');} else {alert('not exist');}}</script> <button onclick="test()">sutff</button>

Re: JavaScript Function detection?

Posted: Thu Jan 29, 2009 3:44 pm
by VladSun
It's not about anyone's style:

func() - a call to a function
func - a pointer to a function (its address)

pickle's code won't work in IE (mine is ver. 8 ) - it will pop up a JS error message box if hello() doesn't exist.

[js]function a(){} if (typeof(a) == 'undefined')    alert('undefined');else    alert('defined');[/js]

Re: JavaScript Function detection?

Posted: Thu Jan 29, 2009 5:11 pm
by JAB Creations
Vlad, the code put in to functions works just fine in IE6 and IE8 (both system not standalones, IE6 is in Virtual PC and IE8 system IE on XP)...

Code: Select all

<script>function a(){} function b(){if (typeof(a) == 'undefined')    alert('undefined');else    alert('defined');}</script> <button onclick="b()">sutff</button>
...the reason for this is I will do function detection for user JavaScript functions at some point in Version 2.9 of my site. My site's functions will be very slightly altered to let users adjust those functions by creating "user_" prefix named functions. That way people can not only suggest improvements but make scripts as well as show if their scripts work better. :D