Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!