Reputation: 1645
In the chapter on Bugs and Error Handling in Eloquent Javascript, I found the following piece of code. I would like to know why the writer set the name property on the prototype--not in the constructor.
function InputError(message) {
this.message = message;
this.stack = (new Error()).stack;
}
InputError.prototype = Object.create(Error.prototype);
InputError.prototype.name = "InputError";
Throughout the book, he has been defining properties in the constructor and methods on the prototype. Nicholas Zakas recommends doing the same in Ch6 of Professional Javascript for Web Developers, because, he says, if you define methods in the constructor, then each call to the constructor creates a new instance of the method. This is of course the opposite situation--a property being defined on the prototype.
To reiterate: What I want to know is, why might the author have defined 'name' property on the prototype?
So far, I've read these two SO posts two no avail.
-This told me what I've already read in the books mentioned above.
Why defining properties in the prototype is considered an antipattern
-I didn't really understand this post, but I think it was irrelevant, because it was talking about patterns in other languages. I am concerned with javascript.
Upvotes: 0
Views: 59
Reputation: 1645
Every InputError
shares the same name. The only thing that really needs to change in each new instance is the message
argument. In this case, it doesn't really matter.
Upvotes: 0
Reputation: 817208
Why might the author have defined 'name' property on the prototype?
Because every instance of InputError
shares the same name
. "Methods" is just a colloquial term for properties who have a function as value (*). Usually it is those methods that should be shared between instances, but in some cases (like this one) it might be data as well.
*: Meaning, there is no difference between between a property and a method.
Upvotes: 2