I am using John Resig’s inheritance implementation for my current project, and I was wondering if there is a way for subclass to also inherit(access) parent’s closure variable…
for example, I write the following class
var Foo = (function() {
var p = "im p";
var Foo = Class.extend({
getp : function() {
return p;
}
});
return Foo;
})();
now Foo class has access to the variable p in the closure. so are Foo’s subclass…
var Bar = Foo.extend({});
var bar = new Bar;
bar.getp(); // "im p"
this is no surprise since bar.getp simply call Foo.getp, which has access to p. however if i overwrite bar.getp
var Bar = Foo.extend({
getp : function() {
return p;
}
});
now when I do bar.getp(), it will throw p is undefined since it is not accessible to bar
I have several methods in mind to make p accessible to bar, but I think they are little awkward, what you think is the cleanest way to accomplish this.
Closure scope consists of anything that’s in scope when the function is defined. In this case,
pis in scope when the firstgetpis defined, but not when the secondgetpis defined. So you can’t referencep. In fact, what you might have discovered is that thepreferenced by the firstgetpmethod is actually universal to allFooobjects (and their sub-classes).JavaScript doesn’t really lend itself to “private variables” very well. Generally, developers end up using either closure scoped variables when inheritance is not needed or some sort of convention when inheritance is needed, such as adding an underscore, like this:
Then you can subclass without difficulty:
Now, I should also note that your example is pretty contrived and is contrived in a way as to be a bit pointless. I mean, why override
getp()with something that also just returnsp? If your intention was to actually create a private, static propertyp, then what you have should work fine. If you want access topin subclasses, you should just use thegetpmethod that you have access to, like this:Hope that helps!