gpt4 book ai didi

JavaScript 继承没有像我预期的那样工作

转载 作者:行者123 更新时间:2023-11-30 15:21:10 25 4
gpt4 key购买 nike

pe.getName() 有效而 pe.getSalary() 无效的详细信息是什么?

var Employee = function(name) {
this.name = name;
}

Employee.prototype.getName = function() {
return this.name;
}

var PermanentEmployee = function(annualSalary) {
this.annualSalary = annualSalary;
}

PermanentEmployee.prototype.getSalary = function() {
return this.annualSalary;
}

var employee = new Employee("Mark");

PermanentEmployee.prototype = employee;

var pe = new PermanentEmployee(5000);

document.write(pe.getName());
document.write(pe.getSalary());

最佳答案

稍后在您的代码中执行此操作

PermanentEmployee.prototype = employee;

你可以覆盖这个

PermanentEmployee.prototype.getSalary = function()

试试这个:

function Employee(name) {
this.name = name;
}

Employee.prototype.getName = function() {
return this.name;
}

function PermanentEmployee(name, annualSalary) {
Employee.call(this, name); // calling parent's "constructor"
this.annualSalary = annualSalary;
}
PermanentEmployee.prototype = Object.create(Employee.prototype); // setting "inheritance"
PermanentEmployee.prototype.getSalary = function() {
return this.annualSalary;
}
var pe = new PermanentEmployee("Mark", 5000);

console.log(pe.getName());
console.log(pe.getSalary());

关于JavaScript 继承没有像我预期的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706801/

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