Thursday, 5 September 2013

Simple 'static' in Javascript 'base class'

Simple 'static' in Javascript 'base class'

I've read through most of the Javascript inheritance references, but I'm
afraid I'm still scratching my head as to how to do this.
I'm trying to put together several classes, in the general sense, that
will have similar behavior and thought using prototypes might be a way to
achieve that. So I create a base class as follows:
function my_base_class()
{
var a_common_object = undefined; // The true value of this can't be
set until runtime.
// some other stuff ...
};
Ideally, I'd like a_common_object to be private or at least protected, but
just getting it working would be a good first step. I then need to create
several derived classes of which this might be one:
function my_derived_class()
{
this.do_something_to_common_object = function()
{
// Here I need to reference my_base_class.a_common_object but
// at this point there's no relationship between the two classes
};
};
I now set the prototype of my_derived_class while creating an instance:
my_derived_class.prototype = new my_base_class();
var my_derived_class_inst = new my_derived_class();
So at this point I'm hoping that I have an object - my_derived_class_inst
which has traits of my_base_class including the static object
a_common_object which I can access.
I have two questions:
How do I refer to a_common_object within my_derived_class when there's no
relationship established between the two classes?
How can I then change a_common_object to its true value, so that all
derived classes seamlessly pick up the new value.
Please don't simply refer me to the standard reference web sites on
inheritance as I've read most of them through and I'm still no wiser. It
seems to me that the answer should be really simple but so far it escapes
me. Many thanks.

No comments:

Post a Comment