[英]prototypal inheritance javascript
我在使用構造函數 function 在 JavaScript 中實現原型 inheritance 時遇到錯誤。
我正在嘗試像這樣實現自定義(用戶定義)原型鏈 -
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
請參閱mdn 文檔以了解為什么它不起作用
更好的使用:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.