[SOLVED] prototypal inheritance javascript

Issue

This Content is from Stack Overflow. Question asked by Aman Ghanghoriya

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.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;
}

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 



Solution

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();


This Question was asked in StackOverflow by Aman Ghanghoriya and Answered by Konrad Linkowski It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?