I have a variable obj
obj can be anything, and I want to detect if obj is a function. Normally I would do
typeof obj === 'function'
The problem is in IE <= 8 when obj is a native function (at least know it happens with window.open and window.alert). In IE typeof obj when object is window.open === 'object'
Is there a reliable way to check if window.open is actually a function or not?
I see jQuery also fails on this
$.isFunction(window.open) => false //in IE
this apperantly got removed in jquery 1.3 or something, not sure how they tested it before that.
Added: One way seem to be to call
Function.prototype.apply.apply(window.open)
If this does not throw an error, then window open is a function. If you do
Function.prototype.apply.apply({})
Then IE throws an error "Function expected". But it is hardly a good solution to open a window to check if a variable is a function..
When it comes to native browser functions, feature detection should be sufficient:
if (window.open) {
window.open(...)
}
If someone overwrites native functions, then don't use their code. They shouldn't be doing this, and you are asking for problems.
It's also difficult to answer this question without some context. You are passing in obj
and invoking it as a function. If you are passing in multiple data types and doing something different based on the type, I would argue that you shouldn't be handing functions here. Because of browser quirks, create a function explicitly to dynamically call another function and don't do error checking.
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