I am learning Prototypal Inheritance in JavaScript. I have encountered this weird thing while calling methods and variables of child class object whose prototype is parent class object. Refer to the code below.
class childX {
vehicleType = "Not Available";
methX(){
console.log("Hello from the ChildX object");
}
}
class ParentX {
vehicleType = "Truck";
methX(){
console.log("Hello from the ParentX object");
}
}
let childObj = new childX();
let parentObj = new ParentX();
childObj.__proto__ = parentObj;
console.log("Child Vehicle Type: ", childObj.vehicleType);// output: Not Available
childObj.methX(); // output: Hello from the ParentX object
You should use the extends keyword
But if you really don't want to do this use
Object.setPrototypeOfas shown here