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 1:
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);