| re: trouble passing parameters of a subclass constructor through to it's superclass constructor
ingoweiss wrote:[color=blue]
> Hi,
>
> I am having trouble passing parameters of a Javascript subclass
> constructor through to it's superclass constructor.
>
> I am trying all sorts of things, including the below, but nothing
> worked so far.
>
> Thanks for any help!
>
>
>
>
> function Base(a)
> {
> this.a = a;
> }
>
> function Derived(a)
> {
> this.prototype.constructor.call(a);
> }
>
> Derived.prototype = new Base();
> Derived.prototype.constructor = Derived;
>
> var derived = new Derived("hello");
> //a should be "hello" now, but it is undefined:
> window.alert(derived.a)[/color]
Be careful with an a la class inheritance in the conventional
JavaScript (thus not JScript.Net and such). Be careful exactly because
it's an "a la class inheritance", not "the class inheritance".
Everything can work pretty close to what you may used to in other
languages, but many features are emulated or missing.
And for sure you shouldn't use both prototype inheritance and class
inheritance together. Fists of all it's a needless mess, secondly it's
error prone, finally (as you just discovered) it simply doesn't work in
the way you think it should work.
// by keeping (a la) class inheritance:
function Base(a) {
this.foo = 'bar';
this.a = a;
}
function Derived(a,b) {
Base.call(this,a);
this.b = b;
}
var obj = new Derived('a','b');
alert(obj.foo);
alert(obj.a);
alert(obj.b); |