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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
Footo a method which only accepts objects of typeBar* and you’ll get a compiler warning.And now for the actual explanations
prototypeorconstructorafter creation (read:new), you can change the object’s properties.What are you actually trying to do?
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
Fooisn’t a subtype ofBar, 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