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

JavaScript继承没有像我预期的那样工作,javascript,inheritance,prototype,Javascript,Inheritance,Prototype,为什么pe.getName()工作而pe.getSalary()不工作的详细信息是什么 var Employee=函数(名称){ this.name=名称; } Employee.prototype.getName=函数(){ 返回此.name; } var PermanentEmployee=功能(年度){ this.annualSalary=annualSalary; } PermanentEmployee.prototype.getSalary=函数(){ 把这个退给我。每年一次; }

为什么
pe.getName()
工作而
pe.getSalary()
不工作的详细信息是什么

var Employee=函数(名称){
this.name=名称;
}
Employee.prototype.getName=函数(){
返回此.name;
}
var PermanentEmployee=功能(年度){
this.annualSalary=annualSalary;
}
PermanentEmployee.prototype.getSalary=函数(){
把这个退给我。每年一次;
}
var员工=新员工(“标记”);
PermanentEmployee.prototype=员工;
var pe=新的永久雇员(5000);
document.write(pe.getName());

document.write(pe.getSalary())稍后在代码中执行此操作

PermanentEmployee.prototype = employee;
你可以忽略这个

PermanentEmployee.prototype.getSalary = function()
请尝试以下方法:

职能员工(姓名){
this.name=名称;
}
Employee.prototype.getName=函数(){
返回此.name;
}
职能永久雇员(姓名、年薪){
Employee.call(this,name);//调用父级的“构造函数”
this.annualSalary=annualSalary;
}
PermanentEmployee.prototype=Object.create(Employee.prototype);//设置“继承”
PermanentEmployee.prototype.getSalary=函数(){
把这个退给我。每年一次;
}
var pe=新的永久雇员(“马克”,5000);
log(pe.getName());

log(pe.getSalary())这实际上是预期的行为。如果你想了解原因,我们开始

考虑以下模式,可在Axel Rauschmayer博士的优秀著作中找到

在继续之前,这里有一条重要规则:在JavaScript中,当您创建“类”的实例时,该实例将通过其dunder proto引用其构造函数的prototype属性(
\uu proto\uuu
[[prototype]]

左上角 在您的示例中,
Employee
PermanentEmployee
是构造函数。与JavaScript中的任何函数一样,它们是
function
的实例,并且使用
function.prototype

var Employee=函数(名称){
this.name=名称;
}
var PermanentEmployee=功能(年度){
this.annualSalary=annualSalary;
}
console.log(typeof Object.getPrototypeOf(Employee));//ES5
console.log(永久雇员的类型)ES6
console.log(Object.getPrototypeOf(Employee.constructor);//ES5

console.log(PermanentEmployee.\uuu proto\uuuu.constructor);//ES6
但在我的代码背后实际发生了什么。。请解释一下。您将
PermanentEmployee
对象的\uproto\uref.重置为
employee
对象和函数
getSalary()
(在通过
PermanentEmployee
对象的\uproto\uref.可访问的对象中),然后才变得不可访问。由于
getSalary()
PermanentEmployee
对象中不再可访问,因此JS尝试在原型链中找到它,并转到
employee
对象,该对象既没有此类方法,也没有对
getSalary()对象的引用
方法本身通过其uu proto\uu,最后抛出一个错误,因为在任何地方都找不到
getSalary()
方法。这是Javascript非常重要的核心部分,您希望从一开始就获得它。我尽了最大的努力来解释上面的内容,这对我来说非常准确,但对新手来说可能听起来很困惑,所以,你应该找到更多更详细地介绍这个主题的材料。这是我的建议。谢谢你,先生,它帮了我一点忙。。。我想我必须了解更多关于prototype和Inhertance的知识,所以我在构造函数中声明
getSalary()
方法,然后它会工作吗。?