javascript - Javascript函数错误中的继承

标签 javascript inheritance

我通过以下方式在 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/

相关文章:

javascript - 如何从 SAP UI 中的表中获取数据?

javascript - HTML5 可拖动列表 - 多个 setData?

javascript - 使用 .hover() 时如何用链接标记替换文本?

javascript - 如何在 Qt Creator 中的 main.cpp 文件之外声明函数

c# - 如何获取基类型字段的值

qt - 是否可以使用 "this"从派生对象的基类发出信号

delphi - 当我调用基类上的方法时,如何调用后代的实现?

javascript - 初学者在这里。我需要帮助更好地理解这个回调函数

公共(public)领域方法的继承或服务?

python - Django模型继承: create sub-instance of existing instance (downcast)?