0

I'm trying to use prototypal inheritance and its not working, everytime i try i keep getting undefined:

function HospitalEmployee(name) {
  this._name = name;
  this._remaningVacationDays = 20;
}

function Nurse() {}

Nurse.prototype = Object.create(HospitalEmployee.prototype)

const nurseOlynyk = new Nurse("Olynyk", ["Trauma", "Genetics"])

console.log(nurseOlynyk._remainingVacationDays) //Prints undefined

What am i doing wrong?

  • The `Nurse` constructor doesn't call the `HospitalEmployee` constructor… – deceze May 13 '22 at 07:08
  • @deceze Why is function prototype so strict!? – Random User May 13 '22 at 07:13
  • 1
    Cause that's how it works. `new Nurse` calls the function `Nurse`, which doesn't do anything. It doesn't implicitly call `HospitalEmployee`, because there's no direct link there. Using this kind of prototypical inheritance is very bare metal. You only get this implicit behaviour with the nicer `class` syntax, which papers over all those details. – deceze May 13 '22 at 07:15
  • I would suggest you to take a look at the topic "inheritance vs composition" in javascript. – MatteoPHRE May 13 '22 at 07:16
  • @deceze And now JavaScript throws a referenceerror saying that HospitalEmployee is not defined when using HospitalEmployee.call() – Random User May 13 '22 at 07:20
  • Uhm, no, then you've done something wrong… – deceze May 13 '22 at 07:21
  • @deceze Yeah i did – Random User May 13 '22 at 07:32

1 Answers1

0

I need use Class and Extends for it same as :

class HospitalEmployee {
  constructor(name){
    this._name = name;
    this._remaningVacationDays = 20;
  }
}
class Nurse extends HospitalEmployee {
  constructor(name, otherParams){
    super(name);
    this.otherParams = otherParams;
  }
}
const nurseOlynyk = new Nurse("Olynyk", ["Trauma", "Genetics"])
console.log(nurseOlynyk)
Xupitan
  • 1,601
  • 1
  • 8
  • 12