Node.js NodeJS中的原型遗传

Node.js NodeJS中的原型遗传,node.js,Node.js,我正在学习NodeJS和原型遗传 下面是我用于原型继承的代码 我面临的问题是: meow、purr和hiss方法确实会在leopardObj上被调用 但是,每当我调用下面的方法时,在这些方法中,this.name总是以未定义的形式出现 leopardObj.meow(); leopardObj.purr(); leopardObj.hiss(); 我不明白为什么这个名称是未定义的,有人能帮我吗 function Cat(name){ console.log("Inside C

我正在学习NodeJS和原型遗传

下面是我用于原型继承的代码

我面临的问题是:

meow、purr和hiss
方法确实会在
leopardObj
上被调用

但是,每当我调用下面的方法时,在这些方法中,
this.name
总是以未定义的形式出现

leopardObj.meow();
leopardObj.purr();
leopardObj.hiss();
我不明白为什么
这个名称
是未定义的,有人能帮我吗

function Cat(name){
    console.log("Inside Cat before = ",name);
    this.name = name
    console.log("Inside Cat after = ",this.name);
}
Cat.prototype.meow = () => {  
    console.log(this);
    console.log("Meow for !!",this.name);
}


function Lynx(name){
    console.log("Inside Lynx with name = ",name);
    Cat.call(this,name);
}
Lynx.prototype = Object.create(Cat.prototype);
Lynx.prototype.purr = () => {
    console.log("Purr for !! ",this.name);
}


function Leopard(name){
    console.log("Inside Leopard with name = ",name);
    Lynx.call(this,name);
}
Leopard.prototype = Object.create(Lynx.prototype);
Leopard.prototype.hiss = () => {
    console.log("Hiss for !! ",this.name);
}
const leopardObj = new Leopard("Sheryl");
leopardObj.meow();
leopardObj.purr();
leopardObj.hiss();

meow
purr
hiss
函数都是函数,因此您的上下文绑定不正确。将其更改为常规功能,一切都将按预期工作:

Leopard.prototype.hiss=function(){
log(“Hiss for!!”,this.name);
}