Using the instanceof operator is not recommended as it fails across frames and windows as the constructor.prototype in the origin context is different to the one in the testing context (and different objects are never ==
or ===
).
There are other options.
You can get the error object's class, but that typically just returns "[object Error]":
Object.prototype.toString.call(new ReferenceError()); // [object Error]
However, you can also use the name property which is set to the name of the constructor, so:
new ReferenceError().name; // ReferenceError
is more reliable than instanceof. E.g.:
try {
undefinedFunction();
} catch (e) {
if (e.name == 'ReferenceError') {
console.log(`Ooops, got a ${e.name}. :-)`);
} else {
console.log(`Ooops, other error: ${e.name}. :-(`);
}
}