What is the proper way to get the Child object to inherit its parents values when they are passed into the constructor vice being hard coded?
In the snippet I am passing in four properties yet the Child does not get those values unless I put them directly in. As you see the console log comes up with null NaN undefined if I use arguments when creating an instance of Parent.
class Parent {
constructor(x, y, w, h) {
this.x = x; //if I put values directly here it works
this.y = y;
this.w = w;
this.h = h;
}
}
class Child extends Parent {
constructor() {
super();
this.pt1 = {x: this.x, y: this.y};
this.pt2 = {x: this.x + this.w, y: this.y};
this.pt3 = {x: this.x + this.w, y: this.y + this.h};
this.pt4 = {x: this.x, y: this.y + this.h};
}
}
let parent = new Parent(300, 50, 50, 200);
let child = new Child();
console.log(child.pt1)
console.log(child.pt3)
As you see below by not passing them in as arguments the child is now able to inherit the Parent values. They objects are linked so let's not say they have no relation.
class Parent {
constructor() {
this.x = 300;
this.y = 50;
this.w = 50;
this.h = 200;
}
}
class Child extends Parent {
constructor() {
super();
this.pt1 = {x: this.x, y: this.y};
this.pt2 = {x: this.x + this.w, y: this.y};
this.pt3 = {x: this.x + this.w, y: this.y + this.h};
this.pt4 = {x: this.x, y: this.y + this.h};
}
}
let parent = new Parent();
let child = new Child();
console.log(child.pt1)
console.log(child.pt3)
The parent and child are class objects and they dont have relation each other. From your code, when you call let child = new Child(), you did nothing with the x, y, w and h in your Child constructor.
The Classes are templates, the inheritance means you copy the parent's methods implementation.
You can just think the Parent and Child classes are different each other - just the Child class has all the methods that the Parent has.
When you inherit a class, you need to pass the parameters that the Parent class needs in its constructor.
You can fix it like below:
class Parent {
constructor(x, y, w, h) {
this.x = x; //if I put values directly here it works
this.y = y;
this.w = w;
this.h = h;
}
}
class Child extends Parent {
constructor(x, y, w, h) {
super(x, y, w, h); // <- Passing the parameters
this.pt1 = {x: this.x, y: this.y};
this.pt2 = {x: this.x + this.w, y: this.y};
this.pt3 = {x: this.x + this.w, y: this.y + this.h};
this.pt4 = {x: this.x, y: this.y + this.h};
}
}
let parent = new Parent(300, 50, 50, 200);
let child = new Child(300, 50, 50, 200); // <- pass the values
console.log(child.pt1)
console.log(child.pt3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With