On Sat, 12 Nov 2011 16:46:28 +0000, John G Harris
[snip]
That appears to be about what I was thinking of. It was
confusing code for me. I was looking for a JavaScript keyword "base"
at first. Why is base a property rather than declared local with var?
Does it even matter?
<snip>
It matters very much, and here's why :
Lets assume that we're constructing one of your Commercial objects. In
the constructor you need to create and set the extra properties that you
have in Commercial objects, PropertyZoning and PropertyUse. This is
straightforward :
this.PropertyZoning = PropertyZoning;
this.PropertyUse = PropertyUse;
But you also need to create and set the properties that you have in
RealEstate objects, PropertyLocation and PropertyValue. You could do it
directly in the same way, but this is repeating code that is already in
the RealEstate constructor.
Rewriting code is bad and should be avoided if possible. It is tedious,
even with copy and paste. It is error prone : you might get it wrong.
And one day you will want to change the base constructor so you have to
edit code all over the program to keep it all in step. (Will you get
that right?)
It's much better to run the RealEstate code to do the job for you. Can
you do this?
First, you need to be able run RealEstate as an ordinary function as we
don't want to build another new object. Can this be done? Yes it can!
You simply don't write 'new' in front of it. (Attention Mr Crockford).
Second, you need to call RealEstate with the new Commercial object as
the 'this' value. This is easy using RealEstate's call method :
RealEstate.call(this, [PropertyLocation, PropertyValue]);
// 'this' is the new Commercial object
However, back when I was writing my javascript note 'call' was new and
not in all popular browsers so an older clumsier way was needed.
Remember that if you do a.b() then the function b is called with the
'this' value set to a. So, we create a property of the Commercial object
under construction with the name 'base' (because that's what Netscape
called it and there isn't a really better name), and use it to hold the
function object RealEstate. Now it's easy :
this.base(PropertyLocation, PropertyValue);
// 'this' is the new Commercial object
After using it you delete the temporary property 'base' because it's no
use for any other job.
There you have it. No matter how complicated the base constructor is,
and no matter if the base itself is derived, it runs properly in the
derived constructor. Your only effort is to feed it the right arguments.
John