Reputation: 757
In which condition will Object.prototype.toString.call(fn) === '[object Function]'
and typeof fn === 'function'
return different results?
I saw the function isCallable
on mdn (see line 4 - line 7):
var isCallable = function (fn) {
var toStr = Object.prototype.toString
return typeof fn === 'function' || toStr.call(fn) === '[object Function]'
}
I'm wondering the difference between these two tests, is one of them superfluous?
Upvotes: 4
Views: 367
Reputation: 17721
Object.prototype.toString
returns the value of the object's internal [[Class]] property, it isn't really a Type.
The value of this internal property represents the specification defined classification of an object (more info here).
The value of the [[Class]] internal property for host objects -as DOM elements- can be anything, it is completely implementation-dependent.
So, the best way to test whether fn
is a function is to use typeof fn
.
Not only is it faster but the ECMAScript specification ensures that all functions have a type of "function" and that only functions can have a type of "function" (see also https://stackoverflow.com/a/17108198/709439).
Upvotes: 2