Reputation: 11602
I have always used (typeof variable === "function")
and I stumbled across jQuery.isFunction()
and I was wondering:
Upvotes: 8
Views: 20147
Reputation: 21
Usually you can test whether JS object is function by using this test:
(typeof fn === 'function')
However, this doesn't always work (IE8):
typeof alert => 'object'
typeof document.createElement('input').getAttribute => 'object'
Before jQuery 1.4 internally they used the same check, but now they've fixed it. So to be sure that passed object is a function which can be called, just use $.isFunction method:
$.isFunction(function() {}) => true
$.isFunction(alert) => true
$.isFunction(document.createElement('input').getAttribute) => true
Copied from this blog: http://nuald.blogspot.co.uk/2012/07/why-jqueryisfunction.html
Upvotes: 2
Reputation: 13713
The jQuery source code for isFunction is
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
//...
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "),
function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
core_toString = Object.prototype.toString,
hence jQuery.isFunction
returns true if and only if calling Object.prototype.toString.call
on its argument returns [object Function]
.
Upvotes: 2
Reputation: 96810
There's no difference. jQuery uses the same concept:
// ...
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
}
Update:
After digging in deeper I found that jQuery's isFunction
method is comparing the toString
method of the Object.prototype
chain on function() {}
, to the string [object Function]
. This is the how it differs from your former example and the reason for it being slower than typeof
.
Upvotes: 4
Reputation: 11122
There is almost no difference, other than that using jQuery is slightly slower. See the source code:
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
which calls a function which calls another function to determine the exact same thing as what you showed :P
There is literally no advantage to jQuery in this case [or for that manner, 90% of the use-cases of the library]. Look into Vanilla-JS and check out some of its features :P
TLDR: Don't use jQuery for this...or anything.
Here's a benchmark showing you that Vanilla JS is roughly 93% faster than jQuery: http://jsperf.com/jquery-isfunction-vs-vanilla-is-function.
Upvotes: 11
Reputation: 3498
The difference is that JQuery calls something equivalent to the following and checks for the "Function" string token:
var toString = Object.prototype.toString;
var func = function(){};
console.log(toString.call(func)); // "returns [object Function]"
Whereas typof, just returns "function":
var fType = typeof func;
console.log(fType); // returns "function"
Upvotes: 1