2

I am learning "Error Handling in JavaScript" and read articles on site point. In the articles, it shows the way to make custom error type:

function DivisionByZeroError(message) {
  this.name = "DivisionByZeroError";
  this.message = (message || "");
}

DivisionByZeroError.prototype = new Error();
DivisionByZeroError.prototype.constructor = DivisionByZeroError;

However, I can not understand why the function constructor has to assign to itself again. That is,

DivisionByZeroError.prototype.constructor = DivisionByZeroError;

I think this is because DivisionByZeroError.prototype assigned to new Error() so the prototype was changed.

But I am not sure why even after commenting out that line. The code still works fine.

Demo code is put on jsfiddle


Reference:
Exceptional Exception Handling in JavaScript
A Guide to Proper Error Handling in JavaScript

2

1 Answer 1

1

The reason behind this, is that if you run the following code:

console.log(new Error().constructor)

it outputs:

"ƒ Error() { [native code] }"

Now, by standard, if you create a class, then the following should be true:

console.log(new MyClassName().constructor === MyClassName)

for example, the following is true:

(new Error().constructor) === Error; // true

A use for this could be like so:

function isArray(maybeArray) {
  return maybeArray.constructor === Array;
}
isArray([]); // true
isArray(new Array(10)); // true
isArray(false); // false

// or say this function
function makeAnotherOfObjectWithoutParameters(object) {
    return new object.constructor();
}
(makeAnotherOfObjectWithoutParameters([])); // empty array

So now say you want to see if an object is a DivisionByZeroError. You have your function like so:

function DivisionByZeroError(message) {
  this.name = "DivisionByZeroError";
  this.message = (message || "");
}

DivisionByZeroError.prototype = new Error();

now, you should expect the following to be true:

console.log(new DivisionByZeroError('my message').constructor === DivisionByZeroError);

but you would be surprised that it is false, so now you have to explicitly set the constructor like so:

DivisionByZeroError.prototype.constructor = DivisionByZeroError

and now the above code will work!

Hope this helped someone... I learnt something too!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.