I have come across prototype inheritance in javascript.
What I wanted to achieve is an outline of methods, which when are inherited must be implemented/defined.
I would like to know if this is possible and if so, how.
I have come across prototype inheritance in javascript.
What I wanted to achieve is an outline of methods, which when are inherited must be implemented/defined.
I would like to know if this is possible and if so, how.
JavaScript really doesn't have anything like this. As you said, JavaScript is prototype-oriented.
As other answers have said, sure, you can simulate this. But I can't see a good reason to do so. Why do object-oriented programmers use interfaces and abstract classes? Astraction and decoupling. These allow you to do all sorts of nice things, like write methods that consume (take as arguments) and produce (return) values that have abstract types - objects that will at least satisfy some contract regarding its methods and fields.
In turn, we get other "nice things" like compile-time checks for type safety. Try to pass an object of type Foo
to a method which only accepts objects of type Bar
* and you'll get a compiler warning.
prototype
or constructor
after creation (read: new
), you can change the object's properties.It sounds like you're trying to impose the relative rigidity of strongly-typed, object-oriented languages onto JavaScript's "relaxed, go-with-the-flow" dynamic type system. IMHO, that's not a great idea. Maybe you could explain the actual problem you're trying to solve?
Sorry if this is long-winded, rant-y, or incoherent. I'm sure there's at least one language out there (OCaml?) that totally throws a wrench in my logic. Throw me some feedback.
*Assuming Foo
isn't a subtype of Bar
, of course.
† ...but only at runtime, so it's really no more of a guarantee than what you already get with JavaScript's type system.
‡ thus possibly
Javascript doesn't support it out of the box, but it is easy to simulate the desired semantics. If you have a base 'class' that you want to be abstract, put the method(s) that is (are) abstract on it, and have them throw an error. If the user extends your 'class' and does not provide an implementation, the error will be thrown. For example, you can do
function Thing() {...}
Thing.prototype.abstractMethod = function() {
throw 'You must implement abstractMethod';
}