0

I am learning NodeJS and learning prototypal inheritance.

Below is the code I am using for prototypal inheritance .

The issue I am facing is :

The meow, purr and hiss methods do get called on leopardObj.

But , whenever I call below methods , inside those methods , this.name is always coming as undefined.

leopardObj.meow();
leopardObj.purr();
leopardObj.hiss();

Can anybody please help me as I am not able to understand why this.name is coming as undefined ?

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();

1 Answer 1

1

meow, purr and hiss functions are arrow functions, so you have bind your context incorrectly. Change them to regular functions back and everything will work as expected:

Leopard.prototype.hiss = function() {
    console.log("Hiss for !! ", this.name);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.