J
John G Harris
IMO what's actually confusing about prototypes in javascript is that the
language tries to hide the prototypes behind constructor functions,
which when taken at face value (i.e. when you're making assumptions
based on the semantics of well known class-oriented systems) break at
the point where you start using "class" inheritance, and *then* you have
to re-think the way you're building objects. And then constructors
become more and more useless. At least, that's what happened to me.
I don't understand why you don't like constructors. In Java and similar
languages the compiler writes part of the constructor's code. The
compiler makes sure that the constructor creates and initialises the
instance's ancestor properties.
But this is javascript. You have to do this work yourself as the
compiler won't do it for you. You have to call the ancestor
constructors, in non-constructor mode, yourself. Or you can duplicate
the code that does the job. (There's usually more than one way to do
anything in javascript).
Likewise, in Java etc the compiler makes sure that the instance can
access its methods and its ancestor methods. It does this in any way it
wants. The programmer doesn't need to know, and probably can't know.
Again, this is javascript, where you have to do it yourself. One obvious
way is to build a prototype chain with a layer of methods attached to
each prototype object. Each object in the chain has to be constructed of
course. The obvious way to do this is to have a constructor for that
particular kind of prototype. (Why are people so frightened of doing
this?)
All this is very tedious and annoying to code. On the other hand, it's
much the same each time and can be done while thinking about the
difficult bits you haven't done yet.
The strange thing is that a prototype system like javascript has is in
principle much easier to comprehend (and implement) than systems where
classes are special.
Having to code it yourself with no help from the compiler means that you
end up with a much better idea of what's going on in the program. It
should also make it easier to understand what's happening in Java etc
where much is hidden from you. This is a Good Thing.
John