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

153
Visualizações
check if class has method in javascript

How to check the existence of move() and run() methods shortly and safely? hasOwnProperty returns false of course for both move and run. dog.prototype is undefined so this isn't a way to start.

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
  move() // this method may exist or not
  {
      console.log(`${this.name} moves over.`);
  }
}
class Dog extends Animal {
  constructor(name) {
    super(name); 
  }
  speak() {
    console.log(`${this.name} barks.`);
  }
  run() // this method may exist or not
  {
      console.log(`${this.name} runs fast.`);
  }
}
var dog = new Dog('Caesar');
// in the real-world situation we don't know the type of "dog" here.

How to check if dog.run() exists and invokable? How to check if dog.move() exists and invokable?

Edit: The marked-for-duplicate Q/A (Check whether class constructor defines method) does not answer my question.

The final comment-note in my original post is important: in the real-world situation we don't know the type of "dog" So, I cannot write Animal.prototype or Dog.prototype because I don't know Animal and/or Dog. All I have is

  • a reference to an object (dog),
  • knowing that dog is created with a new ClassName statement where ClassName is a class defined by the class-syntax.
about 4 years ago · Juan Pablo Isaza
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