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 -
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
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.