snippetjavascriptCritical
How to check if function exists in JavaScript?
Viewed 0 times
howfunctioncheckexistsjavascript
Problem
My code is
However, sometimes my
me.onChange is not a function
I want to degrade gracefully because this is not the most important feature in my program.
Any suggestions on how to make sure that it exists and then only execute
(None of the methods below except try catch one work)
function getID( swfID ){
if(navigator.appName.indexOf("Microsoft") != -1){
me = window[swfID];
}else{
me = document[swfID];
}
}
function js_to_as( str ){
me.onChange(str);
}However, sometimes my
onChange does not load. Firebug errors withme.onChange is not a function
I want to degrade gracefully because this is not the most important feature in my program.
typeof gives the same error.Any suggestions on how to make sure that it exists and then only execute
onChange?(None of the methods below except try catch one work)
Solution
Try something like this:
or better yet (as per UpTheCreek upvoted comment)
if (typeof me.onChange !== "undefined") {
// safe to use the function
}or better yet (as per UpTheCreek upvoted comment)
if (typeof me.onChange === "function") {
// safe to use the function
}Code Snippets
if (typeof me.onChange !== "undefined") {
// safe to use the function
}if (typeof me.onChange === "function") {
// safe to use the function
}Context
Stack Overflow Q#1042138, score: 1632
Revisions (0)
No revisions yet.