1

I have this superclass with two private elements and two methods to access them:

function superclass(a,b) {
    var x = a;
    var y = b;
    this.getX = function() {return x;}
    this.getY = function() {return y;}
}

I want to create a subclass called say "ChildClass" that in its constructor, calls the superclass constructor, giving it the two parameters. So I can say parent = new SuperClass(2,3) I alsow need to be able to say child = new ChildClass(3,4) and when i write something like alert(child.getX()), the browser showuld prompt "3". Does anyone know how to do this?

Cosmin
  • 11
  • 1

1 Answers1

0

IIRC, to create constructor hierarchy in JavaScript, you need to write it on your own.

Which means,

function SuperClass {
}

function SubClass {
  this.inheritFrom = SuperClass;
  this.inheritFrom();
}

SubClass.prototype = new SuperClass();

Or maybe, this is still the preferred technique:

function SuperClass {
}

function SubClass {
}

SubClass.prototype = new SuperClass();
SubClass.prototype.constructor = SubClass;

There are some libs to make JavaScript inheritance less PITA.

And I'd recommend you reading David Flannagan's book on JavaScript, part about prototypes.

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
  • 1
    The question was about a superclass with parameters. You don't address this issue at all in your answer. – beldaz Jan 22 '12 at 09:20