我以下列方式在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());
但它在控制台中显示以下错误:
未捕获的TypeError:pe.getSalary不是函数
有没有人能告诉我这个错误背后的原因是什么?
答案 0 :(得分:6)
这是因为您已将getSalary
添加到对象pEmployee.prototype
所引用的内容,但随后完全替换了 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
语法时的情况。