Test for undefined function in Javascript
So Safari keeps yelling at me for one开发者_JS百科 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!
I actually prefer something along these lines.
if(typeof myfunc == 'function') {
myfunc();
}
Just because something isn't undefined doesn't make it a function.
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.
if (typeof map.getCenter !== 'undefined')
Won't throw an error.
So, better yet, if (typeof map.getCenter === 'function') map.getCenter();
Technically you should be testing if map
is undefined, not map.getCenter()
. You can't call a function on an undefined reference.
However, Google's own tutorial suggests that you invoke your JavaScript that accesses the API in a body.onload handler, so that you do not attempt to reference anything until all of the remote .js files are loaded - are you doing this? This would solve the problem permanently, rather than failing cleanly when your JavaScript executes prior to loading the API.
I have been in the habit recently of using the typeof operator to test for things and types. It returns the type as a string which I think avoids some response type confusion.
if( typeof map.getCenter != 'undefined') ...
I'm not sure if it's more correct, but I find good results with this process.
You should be testing whether map
is undefined. In your current check your are still trying to execute the function call.
Assuming that map.getCenter() is always a function, it's sufficient to just use this check:
if (map.getCenter) {
var x = map.getCenter();
}
The worked solution for me is try and catch
,
const stopPropagation = (e) => {
try {
e.stopPropagation();
} catch (err) {
console.log("error with stopPropagation: " + err.error);
}
}
const triggerClick = (e) => {
stopPropagation(e);
};
精彩评论