fn instanceof Function VS Object.prototype.toString.call(fn) === "[object Function]"

Viewed 128

I see a lot of pros javascript developer testing if an object is a function using

Object.prototype.toString.call(fn) === "[object Function]"

Usually I am using

fn instanceof Function === true

can someone enlighten me. Thank you

1 Answers

instanceof just looks for the constructor property in the prototype chain. See the standard:

@@hasInstance: A method that determines if a constructor object recognizes an object as one of the constructor's instances. Called by the semantics of the instanceof operator.

Which means you can "trick" it:

let Constructor = function(){};
Constructor.prototype = Function.prototype;

let Not_A_Real_Function = function(){};
Not_A_Real_Function.prototype = new Constructor;

let not_a_real_function = new Not_A_Real_Function;

// instanceof
console.log(not_a_real_function instanceof Function); 
// prints true

// Object.prototype.toString
console.log(Object.prototype.toString.call(not_a_real_function) === "[object Function]");
// prints false

// typeof
console.log(typeof not_a_real_function === "function");
// prints false

A downside of Object.prototype.toString however is that you can potentially override it all together, to make it return whatever you want.

let Object = {
    prototype: {
        toString(fn){
            return "foo";
        }
    }
};

let fc = function(){};
console.log(Object.prototype.toString.call(fc) === "foo");


For the sake of completeness:
As @Bergi pointed out,

typeof fn == "function"

is probably the safest way. (See the first snippet)

Related