我通过以下方式在 JavaScript 中应用继承:
var employee = function(name) {
this.name = name;
}
employee.prototype.getName = function() {
return this.name;
}
var pEmployee = function(salary) {
this.salary = salary;
}
pEmployee.prototype.getSalary = function() {
return this.salary;
}
var employee = new employee("mark");
pEmployee.prototype = employee;
var pe = new pEmployee(5000);
console.log(pe.getName());
console.log(pe.getSalary());
但它在控制台中显示以下错误:
Uncaught TypeError: pe.getSalary is not a function
谁能告诉我这个错误背后的原因是什么?
最佳答案
这是因为你在pEmployee.prototype
引用的对象中添加了getSalary
,但是随后完全替换 pEmployee.prototype
与一个新的对象。所以自然地,新对象没有 getSalary
。
您所展示的并不是在 ES5 及更早版本中设置继承的正确方法。相反,请参阅内联评论:
var Employee = function(name) {
this.name = name;
};
Employee.prototype.getName = function() {
return this.name;
};
var PEmployee = function(name, salary) {
// Note call to superclass
Employee.call(this, name);
// Now this level's initialization
this.salary = salary;
};
// This sets up inheritance between PEmployee.prototype and
// Employee prototype (then fixes up the
// constructor property)
PEmployee.prototype = Object.create(Employee.prototype);
PEmployee.prototype.constructor = PEmployee;
// NOW you add the method
PEmployee.prototype.getSalary = function() {
return this.salary;
};
// Usage
var employee = new Employee();
var pe = new PEmployee("Mark", 5000);
console.log(pe.getName());
console.log(pe.getSalary());
参见 my answer here有关更详尽的示例,以及如果您改用 ES2015 的 class
语法会是什么样子。
关于javascript - Javascript函数错误中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50695663/