why javascript prototypal inheritance works different for methods and properties of class?

42 Views Asked by At

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

1

There are 1 best solutions below

0
Konrad On

You should use the extends keyword

class ParentX {
  vehicleType = "Truck";
  methX() {
    console.log("Hello from the ParentX object");
  }
}


class childX extends ParentX {
  vehicleType = "Not Available";
  methX() {
    console.log("Hello from the ChildX object");
  }
  x() {
    console.log('x still works')
  }
}


let childObj = new childX();
let parentObj = new ParentX();

console.log("Child Vehicle Type: ", childObj.vehicleType);
childObj.methX();
childObj.x();

But if you really don't want to do this use Object.setPrototypeOf as shown here

class childX {
  vehicleType = "Not Available";
  methX() {
    console.log("Hello from the ChildX object");
  }
  x() {
    console.log('x still works')
  }
}

class ParentX {
  vehicleType = "Truck";
  methX() {
    console.log("Hello from the ParentX object");
  }
}

Object.setPrototypeOf(childX.prototype, ParentX);

let childObj = new childX();
let parentObj = new ParentX();

console.log("Child Vehicle Type: ", childObj.vehicleType);
childObj.methX();
childObj.x();