My code is
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 with
me.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)
Use an if Conditional Statement The code in the brackets will execute if the function is defined. If instead you just test the function without using the window object, for example as if(aFunctionName) , JavaScript will throw a ReferenceErorr if the function doesn't exist.
The typeof operator gets the data type of the unevaluated operand which can be a literal or a data structure like an object, a function, or a variable. The typeof returns a string with the name of the variable type as a first parameter (object, boolean, undefined, etc.).
A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.
Try something like this:
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 }
I had this problem.
if (obj && typeof obj === 'function') { ... }
kept throwing a reference error if obj happened to be undefined.
In the end I did the following:
if (typeof obj !== 'undefined' && typeof obj === 'function') { ... }
A colleague pointed out to me that checking if it's !== 'undefined'
and then === 'function'
is redundant of course.
Simpler:
if (typeof obj === 'function') { ... }
Much cleaner and works great.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With