I have a set of classes I derive from a base class as following (for example):
function Base(){}
Base.prototype.foo = function() { alert("base"); };
function Derived() {}
Derived.prototype = Object.create( Base.prototype );
Derived.prototype.foo = function() { alert("overridden"); };
var b = new Base();
var d = new Derived();
b.foo();
d.foo();
I would like to add variables to the base class (not Java static-like variables, but those with separate values per class instance). Yet, I would like the Derived class to be able to access them too.
I am no Javascript specialist, I have been playing around a little, but I can’t get it to work. Is this possible to achieve this? Or should I implement setter and getters?
An example:
So, the
Baseclass defines one instance member –'name'. TheDerivedclass defines one additional instance member –'type'.The key part is invoking the
Baseconstructor inside theDerivedconstructor invocation – so, internally, you “set up” the instance as if it were aBaseinstance (you pass in the required arguments), and then you augment the instance with the additional stuff defined only forDerivedinstances.So, in my example above,
bhas one own property –'name', whereasdhas two own properties –'name', and'type'.