-1

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 

1
  • You overrided the object stored in Person.prototype after setting the methods on it. So Person.prototype.printAge and Person.prototype.printAge only exist in the old object. Commented Sep 18, 2022 at 17:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.