Home > Back-end >  prototypal inheritance javascript
prototypal inheritance javascript

Time:09-19

I am getting below error while using constructor function to implement prototypal inheritance in JavaScript.

I am trying to achieve custom (user defined) prototype chain like this -

enter image description here

function Human() {
  this.species = "Homo Sapiens";
}

Human.prototype.run = function () {
  console.log("Running...");
};

function Person(gender, age, name) {
  Human.call(this);

  this.name = name;
  this.gender = gender;
  this.age = age;
}

Person.prototype.printAge = function() {
    console.log(this.age);
}
Person.prototype.printGender = function() {
    console.log(this.gender);
}

function Employee(gender, age, name, dept, salary) {
  Person.call(this, gender, age, name);

  this.department = dept;
  this.salary = salary;
}

Person.prototype = Object.create(Human.prototype);
Person.prototype.constructor = Person;

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

const employee = new Employee("female", 28, "Radha", "Manager", 50000);
employee.run();
employee.printAge();

 Uncaught TypeError: employee.printAge is not a function 

CodePudding user response:

See mdn docs to learn why it's not working

Better use:

Object.setPrototypeOf(
  Derived.prototype,
  Base.prototype,
);

function Human() {
  this.species = "Homo Sapiens";
}

Human.prototype.run = function () {
  console.log("Running...");
};

function Person(gender, age, name) {
  Human.call(this);

  this.empname = name;
  this.gender = gender;
  this.age = age;
}

Person.prototype.printAge = function() {
    console.log(this.age);
}
Person.prototype.printGender = function() {
    console.log(this.gender);
}

function Employee(gender, age, name, dept, salary) {
  Person.call(this, gender, age, name);

  this.department = dept;
  this.salary = salary;
}

Object.setPrototypeOf(
  Person.prototype,
  Human.prototype,
);

Object.setPrototypeOf(
  Employee.prototype,
  Person.prototype,
);

const employee = new Employee("female", 28, "Radha", "Manager", 50000);
employee.run();
employee.printAge();

  • Related