Sometimes you might want to call a function in Javascript but check if the function exists before calling it. This is very simple and is covered in this post.
You can test if a function exists in Javascript by simply testing for the name of it in an if() conditional. One thing to be aware of is that you can't test for the function name by itself (well you can, but if it doesn't exist the Javascript will error out); it's a method of the window object so you need to test for window.function_name like so, where some_function_name_here is the name of the function you wish to test for:
A full Javascript code example is shown below, which tests for both the "foo" and "bar" functions and then writes out to the HTML whether they exist or not.
This will output:
So just remember to test for window.function_name and you can't go wrong.
0 comments:
Post a Comment