Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
fn instanceof Function VS Object.prototype.toString.call(fn) === "[object Function]"

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda