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

96
Views
ES6 instanceof when assigning a type to a variable
const Namespace = {
  "FooFunction": () => {
    class MyError extends Error {
      constructor(message) {
        super(message);
      }
    }
    return {"MyError": MyError};
  }
}

console.log((new (Namespace.FooFunction()).MyError("foo")) instanceof Namespace.FooFunction().MyError);

This prints false. I am looking for a way to use instanceof against a "type stored in a variable" like this. How can I do this - is it possible?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Every time you call Namespace.FooFunction, it creates a new MyError class, so Namespace.FooFunction().MyError == Namespace.FooFunction().MyError will never be true.

If you need to keep the MyError class declaration within the function as you have it, changing as little as possible, we can convert FooFunction to an IIFE, which allows it to return the same MyError class on each call:

const Namespace = {
  "FooFunction": (() => {
    class MyError extends Error {
      constructor(message) {
        super(message);
      }
    }
    return (...arguments) => ({"MyError": MyError});
  })()
}

console.log((new (Namespace.FooFunction()).MyError("foo")) instanceof Namespace.FooFunction().MyError);

Of course a better option would be to add the class to the Namespace object itself:

const Namespace = {
  "MyError": class MyError extends Error {
    constructor(message) {
      super(message);
    }
  },
  "FooFunction": function() {
    return {"MyError": this.MyError};
  }
}

console.log((new (Namespace.FooFunction()).MyError("foo")) instanceof Namespace.FooFunction().MyError);
about 4 years ago · Juan Pablo Isaza Report
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!