You need to call the toString
method directly from the Object.prototype
object:
function isFunction (obj) {
return Object.prototype.toString.call(obj) === "[object Function]";
}
alert(isFunction({})); // false
alert(isFunction(function{})); // true
jQuery has a local variable named toString
that refers to the method on Object.prototype
.
Calling just toString.call(obj);
without declaring a toString
identifier on scope, works on Firefox, Chrome, etc, just because the Global object inherits from Object.prototype
, but this is not guaranteed by the spec.
Object.prototype.isPrototypeOf(window); // false on IE
The article you link to talks about a change that was introduced in the ECMAScript 5th Edition specification to the call
and apply
methods.
Those methods allow you to invoke a function passing the first argument as the this
value of the invoked function.
On ECMAScript 3, if this argument was undefined
or null
, the this
value of the invoked function will refer to the global object, for example:
function test () { return this; }
test.call(null) === window; // true
But that changed in ES5, the value should now be passed without modification and that caused the Object.prototype.toString
to throw an exception, because an object argument was expected.
The specification of that method changed, now if the this
value refers to undefined
or null
the string "[object Undefined]"
or "[object Null]"
will be returned, fixing the problem (thing that I don't think is really good, since both results results feel just wrong, undefined
and null
are not objects, they are primitives... that made me remember typeof null == 'object'
... Moreover I think it messes up with the concept of the [[Class]]
internal property, anyway...)
Now you might wonder why jQuery uses this method to check for a function object, instead of using the typeof
operator?
Implementation bugs, for example in Chrome/Safari/WebKit, the typeof
for RegExp objects returns "function"
, because RegExp objects where made callable, e.g.:
typeof /foo/; // "function" in Chrome/Safari/WebKit
The typeof
operator returns "function"
if the object implements the [[Call]]
internal property, which made objects to be callable.
This was originally introduced by the Mozilla implementations, invoking a RegExp object is equivalent to call the exec
method.