Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading