gpt4 book ai didi

javascript - Javascript函数错误中的继承

转载 作者:行者123 更新时间:2023-12-02 08:06:51 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com