Reputation: 1583
I want to have 3 classes which are related. A Node class a DoorNode class and a SisterDoorNode class.
There are different types of nodes, which all have an id, a position, connections and a few functions.
One of these types are door nodes, which, just like the sister door nodes, have the node type "door", a corresponding element and a few functions. Their id and position are calculated in one way.
Then there are also sister door nodes. They have a different way of calculating the id and the position and also have a boolean that states that they are a sister door node.
This is how I wanted it to look like:
class Node {
constructor(id, pos) {
this.id = id;
this.pos = pos;
this.connections = [];
}
addConnection(c) {
//A few functions all nodes need
}
}
class DoorNode extends Node {
constructor(door) {
//Both of these are needed for all Nodes but are calculated in a different way for DoorNode and SisterDoorNode
let id = this.getId(door);
let pos = this.getPos(door);
super(id, pos);
//Both of these are needed in SisterDoorNode and DoorNode
this.nodeType = "door";
this.correspondingElement = door;
}
getId(door) {
return door.id;
}
getPos(door) {
return door.pos;
}
getDoorSize() {
//Some calculations I need for both DoorNode + SisterDoorNode
}
}
class SisterDoorNode extends DoorNode {
constructor(door) {
super(door);
this.isSisterNode = true;
}
getId(door) {
return door.id + ".2";
}
getPos(door) {
return new Point(door.pos.x + 10, door.pos.y + 10);
}
}
but since I can't use a this before a super() this does not work. What is the best way to solve this problem?
Upvotes: 0
Views: 248
Reputation: 1259
So, you're dead on about not being able to use 'this' before 'super', as there is no 'this' to reference before the base class' constructor has finished running.
There are a few solutions to this, but they involve restructuring your code.
1) pass in the id
and pos
as params, just like the base class is doing.
2) Make getId
and getPos
static methods. ( this will introduce new complexities to do with using static variables )
3) make pos
and id
optional, and set them sometime after the super call.
4) you could just reference the props directly; super( door.id, door.pos )
, but that won't work in your extended class that is doing logic on the id
and pos
Update to include example of using a static function with a super call.
class Foo {
constructor(door) {
super( Foo.GetNodeFromDoor( door ) );
// can now use `this`
}
static GetNodeFromDoor( door ) {
// `this` refers to the static namespace, and not to the instance of the class.
return {
id: door.id + ".2",
pos: new Point(
door.pos.x + 10,
door.pos.y + 10
)
}
}
}
Upvotes: 1