Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for undefined function in Javascript

Tags:

So Safari keeps yelling at me for one specific error.

I'm trying to use Google Maps API and call map.getCenter();. However sometimes, this happens before the map has been fully loaded.

So instead in my function I test for an undefined call like this:

if (map.getCenter() != undefined) 

But that still errors out because I guess it doesn't even like making the call just to test the if the result is undefined or not?

Can I get some help here?

Thanks!

like image 587
slandau Avatar asked May 18 '11 15:05

slandau


2 Answers

I actually prefer something along these lines.

if(typeof myfunc == 'function') {      myfunc();  } 

Just because something isn't undefined doesn't make it a function.

like image 128
Swift Avatar answered Oct 14 '22 01:10

Swift


if (typeof map !== 'undefined' && map.getCenter) {    // code for both map and map.getCenter exists } else {   // if they dont exist } 

This is the right way to check for existence of a function.. Calling the function to test its existence will result in an error.

UPDATE: Snippet updated.

like image 24
Aravindan R Avatar answered Oct 14 '22 00:10

Aravindan R