What is the purpose of an abstract METHOD in javascript?
// A convenient function that can be used for any abstract method
function abstractmethod() { throw new Error("abstract method"); }
// The AbstractSet class defines a single abstract method, contains().
function AbstractSet() { throw new Error("Can't instantiate abstract classes");}
AbstractSet.prototype.contains = abstractmethod;
From "Javascript: The Definitive Guide - 9.7.4 Class Hierarchies and Abstract Classes" I understand the utility of abstract classes in JavaScript. What I don't understand is the necessity or use of setting abstract methods that only throw an error. You can't create an instance of that class, so only instances of the subclasses will exist. They'll each have their own definition for these methods, so开发者_JS百科 why establish an inheritance to a method that just throws a generic error?
Thank you in advance for your guiding response.
I assume that the purpose of this is that it's not a generic error - it's an error that informs you where you went wrong (i.e. you failed to override the method in a subclass). If you didn't define that method, you would get an error saying "Undefined is not a function" (or something similar) and you'd have to spend time hunting around your code to understand why - this way it fails in a more verbose and useful manner.
The other reason, I'd assume, is to indicate the class interface to downstream developers implementing subclasses. Javascript doesn't have any kind of formal interface declaration, so it's helpful to be able to inspect the abstract class and see what methods I'm expected to implement.
精彩评论