In my particular case:
callback instanceof Function
or
typeof callback == "function"
does it even matter, what's the difference?
In my particular case:
callback instanceof Function
or
typeof callback == "function"
does it even matter, what's the difference?
instanceof
also works when callback
is a subtype of Function
, I think
Both are essentially identical in terms of functionality, however, I personally prefer instanceof
because its comparing types rather than strings. Type comparison is less prone to human error, and its technically faster since its comparing pointers in memory rather than having to do whole string comparisons.
I would recommend using prototype's callback.isFunction().
They've figured out the difference and you can count on their reason.
I guess other JS frameworks have such things, too.
Instanceof wouldn't work on fuctions defined in other windows, I believe. Their Function is different than your window.Function.
Coming from a strict OO upbringing I'd go for
callback instanceof Function
Strings are prone to either my awful spelling or other typos. Plus I feel it reads better.
instanceof
in Javascript can be flaky - I believe major frameworks try to avoid its use. Different windows is one of the ways in which it can break - I believe class hierarchies can confuse it as well.
There are better ways for testing whether an object is a certain built-in type (which is usually what you want). Create utility functions and use them:
function isFunction(obj) {
return typeof(obj) == "function";
}
function isArray(obj) {
return typeof(obj) == "object"
&& typeof(obj.length) == "number"
&& isFunction(obj.push);
}
And so on.
Use instanceof because if you change the name of the class you will get a compiler error.
A good reason to use typeof is if the variable may be undefined.
alert(typeof undefinedVariable); // alerts the string "undefined"
alert(undefinedVariable instanceof Object); // throws an exception
A good reason to use instanceof is if the variable may be null.
var myNullVar = null;
alert(typeof myNullVar ); // alerts the string "object"
alert(myNullVar instanceof Object); // alerts "false"
So really in my opinion it would depend on what type of possible data you are checking.
Significant practical difference:
var str = 'hello word';
str instanceof String // false
typeof str === 'string' // true
Don't ask me why.